《Unix环境高级编程》:执行所有的命令行参数以及计时

《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu10.04上测试通过。


程序简介:这个例子将每个命令行参数作为shell命令执行,对每个命令计时,并打印出每次计时结束后从tms结构体中所取得的值。


//《APUE》程序8-18:执行所有的命令行参数以及计时
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/times.h>
#include <unistd.h>

void pr_exit(int status);
void error_quit(const char *str);
static void pr_times(clock_t, struct tms*, struct tms*);
static void do_cmd(char *);

int main(int argc, char **argv)
{
	int i;
	setbuf(stdout, NULL);
	for(i=1; i<argc; i++)
		do_cmd(argv[i]);
	return 0;
}

//输出错误信息并退出
void error_quit(const char *str)
{
	fprintf(stderr, "%s\n", str);
	exit(1);
}

void pr_exit(int status)
{
	if( WIFEXITED(status) )
	{
		printf("normal termination, exit status = %d\n", 
			WEXITSTATUS(status));
	}
	else if( WIFSIGNALED(status) )
	{
		printf("abnormal termination, signal number = %d%s\n", 
			WTERMSIG(status),
#ifdef WCOREDUMP
			WCOREDUMP(status) ? " (core file gererated)" : " no ");
#else
			"");
#endif
	}
	else if( WIFSTOPPED(status) )
	{
		printf("child stopped, signal number = %d\n", 
			WSTOPSIG(status));
	}
}

//执行给定命令并计时
static void do_cmd(char *cmd)
{
	struct tms tmsstart, tmsend;
	clock_t start, end;
	int status;

	printf("\ncommand: %s\n", cmd);
	//开始计时
	start = times(&tmsstart);
	if( -1 == start )
		error_quit("times error");
	//执行命令
	status = system(cmd);
	if( status < 0 )
		error_quit("system() error");
	//结束计时
	end = times(&tmsend);
	if( -1 == end )
		error_quit("times error");

	pr_times(end-start, &tmsstart, &tmsend);
	pr_exit(status);
}

static void pr_times(clock_t real, struct tms *tmsstart, struct tms *tmsend)
{
	static long clktck = 0;
	if( 0 == clktck )
	{
		clktck = sysconf(_SC_CLK_TCK);
		if( clktck < 0 )
			error_quit("sysconf error");
	}

	double temp;
	temp = (double)real / clktck;
	printf("  real: %0.2f\n", temp);
	temp = (double)(tmsend->tms_utime - tmsstart->tms_utime) / clktck;
	printf("  user: %0.2f\n", temp);
	temp = (double)(tmsend->tms_stime - tmsstart->tms_stime) / clktck;
	printf("  sys: %0.2f\n", temp);
	temp = (double)(tmsend->tms_cutime - tmsstart->tms_cutime) / clktck;
	printf("  child user: %0.2f\n", temp);
	temp = (double)(tmsend->tms_cstime - tmsstart->tms_cstime) / clktck;
	printf("  child sys: %0.2f\n", temp);
}


运行示例(红色字体的为输入):

qch@ubuntu:~/code$gcc temp.c -o temp
qch@ubuntu:~/code$ ./temp "sleep 5" "date"


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
2012年 08月 22日 星期三 23:31:58 PDT
  real: 0.02
  user: 0.00
  sys: 0.00
  child user: 0.00
  child sys: 0.02
normal termination, exit status = 0

你可能感兴趣的:(struct,cmd,user,ubuntu,System,Signal)