Unix进程与C编程[前篇]
1. 如何获得进程的运行时间
/* process using time */
#include<stdio.h>
#include<stdlib.h>
#include<sys/times.h>
#include<time.h>
#include<unistd.h>
void time_print(char *,clock_t);
int main(void){
clock_t start,end;
struct tms t_start,t_end;
start = times(&t_start);
/*system() will fork a child process, which will call “bin/sh –c”
*to run the command. */
system(“grep the /usr/doc/*/* > /dev/null 2> /dev/null”);
end=times(&t_end);
time_print(“elapsed”,end-start); //running time of child process.
puts(“parent times”);
time_print(“/tuser CPU”,t_end.tms_utime);
time_print(“/tsys CPU”,t_end.tms_stime);
puts(“child times”);
time_print(“/tuser CPU”,t_end.tms_cutime);
time_print(“/tsys CPU”,t_end.tms_cstime);
exit(EXIT_SUCCESS);
}
void time_print(char *str, clock_t time){
long tps = sysconf(_SC_CLK_TCK);
printf(“%s: %6.2f secs/n”,str,(float)time/tps);
}
2. 进程通信—信号
/* usage of kill,signal,wait */
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<signal.h>
int flag;
void stop();
int main(void){
int pid1,pid2;
while((pid1=fork()) ==-1);
if(pid1>0){
while((pid2=fork()) ==-1);
if(pid2>0){
flag=1;
sleep(5); //first sleep
kill(pid1,16);
kill(pid2,17);
wait(0);
wait(0);
printf(“/n parent has finished, flag=%d/n”,flag);
exit(EXIT_SUCCESS);
}else{
flag=1;
signal(17,stop);
//sleep(2); //second sleep
printf(“/n child2 is killed by parent, flag=%d/n”,flag);
exit(EXIT_SUCCESS);
}
}else{
flag=1;
signal(16,stop);
//sleep(3); //third sleep
printf(“/n child1 is killed by parent, flag=%d/n”,flag);
exit(EXIT_SUCCESS);
}
}
void stop(){
flag = 0;
}
说明:
1)
signal(16,stop)
指定类型为
16(16,17是用户自定义型)
的信号的处理方式:调用
stop()
;
2)
我的本子上的
signal
类型如下(30,31是用户自定义型):
![](http://album.hi.csdn.net/app_uploads/yanh_lzu/20081028/112314995.p.gif?d=20081028113122308)
![d](http://album.hi.csdn.net/app_uploads/yanh_lzu/20081028/112946026.p.gif?d=20081028113222198)
3)
若
first sleep
语句被注释,而
second/third sleep
语句不注释,则
stop
会在两个子进程中被调用。上面程序的写法中
stop
不会被执行。
声明:本篇及其后续是我的学习笔记,资料来自网络与书本,本人对其中的程序不声明任何版权。