一:注意頭文件爲<sys/times.h>,time後面有s。
源代碼:
cat -n 8_31.c
1 #include "apue.h"
2 #include <sys/times.h>
3
4
5 static void pr_times(clock_t,struct tms *,struct tms *);
6 static void do_cmd(char *);
7
8 int main(int argc,char **argv)
9 {
10 int i =1;
11 for (i = 1; i < argc; ++i){
12 do_cmd(argv[i]);
13 }
14 return 0;
15 }
16
17
18
19 static void do_cmd(char *cmd)
20 {
21 struct tms start_tms,end_tms;
22 clock_t start,end;
23 int status;
24 printf("\ncommand:%s\n",cmd);
25
26 if ((start = times(&start_tms)) == -1)
27 err_sys("times error");
28 if ((status = system(cmd)) <0 )
29 err_sys("system call error");
30 if ((end = times(&end_tms)) == -1)
31 err_sys("times end error");
32
33 pr_times(end - start,&start_tms,&end_tms);
34 pr_exit(status);
35 }
36
37
38
39 static void pr_times(clock_t real,struct tms *tmsstart,struct tms *tmsend)
40 {
41 static long clktck = 0;
42 if (clktck == 0)
43 if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
44 err_sys("sysconf error");
45
46 printf("real:%7.2f\n",real / (double) clktck);
47 printf("user:%7.2f\n",(tmsend->tms_utime - tmsstart->tms_utime) / (double) clktck );
48 printf("sys:%7.2f\n",(tmsend->tms_stime - tmsstart->tms_stime) / (double) clktck);
49 printf("child user:%7.2f\n",(tmsend->tms_cutime - tmsstart->tms_cutime) / (double)clktck);
50 printf("child sys:%7.2f\n",(tmsend->tms_cstime - tmsstart->tms_cstime) / (double)clktck);
51 }
二 運行結果:
./pr_cmd_time "sleep 5" "date" "man bash > /dev/null"
command:sleep 5
real: 5.02
user: 0.00
sys: 0.00
child user: 0.00
child sys: 0.00
normal termination,exit status = 0
command:date
Mon Nov 2 20:14:51 CST 2015
real: 0.02
user: 0.00
sys: 0.00
child user: 0.00
child sys: 0.00
normal termination,exit status = 0
command:man bash > /dev/null
Reformatting page. Please Wait... done
real: 0.51
user: 0.00
sys: 0.00
child user: 0.47
child sys: 0.08
normal termination,exit status = 0
從命令三可以看出 cpu時間都是在子進程 從而可以推斷出 shell和cmd都是在子進程裏運行的。