课内强化 9(完成时间:2013 年 3 月 31 日)
9.2. 制作一个控制台小时钟,每隔一秒输入一次当前的系统时间。然后扩展程序的灵活性,
允许用户提供输出频率、输出样式等选择
答:
#include
#include
#include
int main(){
int i;
//define
int time_format;
int sleep_time=0;
char *wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat" };
time_t timep;
struct tm *p;
void print_time(int t_f){//choose time format
if(t_f==1){
printf("%d.%d.%d ",(1900+p->tm_year), (1+p->tm_mon),p->tm_mday);
printf("%s\n%d:%d:%d\n\n", wday[p->tm_wday], p->tm_hour, p->tm_min,
p->tm_sec);
}
else if(t_f==2){
printf("%d:%d:%d\n\n", p->tm_hour, p->tm_min, p->tm_sec);
}
else{
printf("choose a wrong format!!!\n");
}
}
system("clear");
while(time_format!=1&&time_format!=2){
//choose time format
printf("choose time format(1 or 2).\n");
scanf("%d",&time_format);
if(time_format!=1&&time_format!=2)
printf("choose a wrong format!!!\n\n");
}
system("clear");
while(!(sleep_time>=1&&sleep_time<=10)){
printf("choose sleep time(1 to 10).\n"); //choose sleep time
scanf("%d",&sleep_time);
if(!(sleep_time>=1&&sleep_time<=10))
printf("choose a wrong time!!!\n\n");
}
system("clear");
for(i=0;i<10;i++){
//print times
time(&timep);
p=localtime(&timep);
print_time(time_format);
sleep(sleep_time);
}
return 0;
}
结果抓图:
9.3 选做题:编写一个程序,该程序可以采用命令行的方式提供参数,测试参数
所指程序的运行时间。可规定完成时间,若在指定时间内未完成则终止被测试
程序。输入的命令行格式如下:
./timetst yourprogram [time]
其中,yourprogram 是被测试程序,time 是规定完成的时间,若不提供或为 0 则
表示无限等待被测试程序。也可使它高级一些,作为扩展可以允许被测试程序
输入参数。
Timetst 代码:
#include
#include
#include
#include
#include
#include
char a[]="pkill ";//与b拼接得到终止程序进程部分
char *b;
void stop(){
system(b);
}
int main(int argc,char *argv[]){
struct timeval tv;
struct timezone tz;
long t_a;
long t_b;
if(argc==1){//若无参数,打印无程序执行
printf("NO program to execute!\n");
}
else if(argc==2){//有一个参数,执行并计算时间
char *arg=argv[1];
gettimeofday(&tv,&tz);
t_a=tv.tv_usec;//读取执行前时间,毫秒计时
system(arg);//执行程序
gettimeofday(&tv,&tz);
t_b=tv.tv_usec;//读取执行后时间,毫秒计时
printf("cost time:%ld ms\n",t_b-t_a);//前后相减,得到执行时间
}
else if(argc==3){//有两个参数,可以被终止
char *arg=argv[1];
char *arg2=argv[2];
int time=atoi(arg2);//终止时间从字符串转换为int型
/*该部消去一切’/’,得到程序的进程名,
如“./a/b/test”变为“test”*/
b=rindex(argv[1],'/');
char *c=malloc(strlen(b)-1);
int i;
for(i=0;i
}
//参数过多,异常打印
else{
printf("The number of parameter are too much!\n");
}
return 0;
}
检测程序Test的代码:
#include
#include
#include
int main(){
int i;
for(i=0;i<10;i++){
printf("sleep%d\n",i+1);
sleep(1);
}
}