linux系统模拟操作,linux下模拟shell的C程序--操作系统作业

在shell中time函数可以输出调试信息,在terminal输入man time了解用法

用自己定义的格式写入一个文件,然后从这个文件读取数据输出

一个模拟shell的supershell就完成了

system()函数

time函数在linux里有2个,一个在batch直接输入time,一个在usr/bin/time,后者可以得到更多信息

程序的输入可以是 % supershell command 单词之间可以有任意空格

command必须是符合要求的输入,不然统计结果会出错

#include

#include

#include

#include

#include

#include

#include

#define N 1000

char input[N];

char cmd[N],tmp[N];

const char sp[]="%U %S %E %F %R %w %W %P";

const char pre[]="/usr/bin/time -o temp.txt -f";

/*get the command from string s, format "% supershell command"*/

int getToken(char *s)

{

int len = strlen(s);

int i=0;

while(s[i] == ' ' && i

if(s[i]!='%'||i>=len) return -1; //not obey format

i++;

while(s[i] == ' '&& i

if(i>=len) return -1;

char temp[]="supershell";

for(int j=0;j

if(s[i]!=temp[j])

return -1;

while(s[i]==' '&& i

if(i>=len) return -1;

return i;

}

/*%U %S %E %P %F %R %w %W*/

/*the process resource information is written in "temp.txt" with format as above*/

void print()

{

FILE *fp;

fp = fopen("temp.txt", "r");

if(fp==NULL)

{

printf("open error\n");

return ;

}

//get information from "temp.txt"

double user_time, sys_time, per,elapsed;

int maj_flt, min_flt, sa, sw;

if(fscanf(fp, "%lf %lf 0:%lf", &user_time, &sys_time, &elapsed)!=3) printf("wrong 1\n");

if(fscanf(fp, "%d %d %d %d %lf", &maj_flt, &min_flt, &sw, &sa, &per)!=5) printf("wrong 2\n");

printf("CPU time %.1lfms (user time %.1lfms, system time %.1lfms)\n", (user_time+sys_time)*1000.0, user_time*1000.0, sys_time*1000.0);

printf("elapsed time %.1lfms\nmajor fault %d, minor fault %d\nswap %d\ncontext switch %d\n", elapsed*1000.0,maj_flt, min_flt, sa, sw);

}

int solve(char *s)

{

/*make format like: /usr/bin/time -o temp.txt -f "%U %S %E %P %F %R %w %W" command*/

strcpy(tmp, s);

strcpy(s, pre);

int j=strlen(s);

s[j++]=' ';

s[j++]='\"';

strcpy(s+j, sp);

j=strlen(s);

s[j++]='\"';

s[j++]=' ';

strcpy(s+j, tmp);

/*output system command*/

printf("command is %s\n", s);

return system(s);

}

int main ()

{

int child_sta=0;

rusage usage;

time_t ep_t1, ep_t2;

while(gets(input))

{

int j = getToken(input);

if(j<0) printf("input not obeying format\n");

else

{

strcpy(cmd, input+j);

int p = strlen(cmd)-1;

while(cmd[p]==' '&&p>=0) p--;

cmd[p+1] = '\0'; // delete white space after command

solve(cmd);

print();

}

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值