Unix进程与C编程[前篇]

 
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(1617是用户自定义型 的信号的处理方式:调用 stop()
2)      我的本子上的 signal 类型如下(30,31是用户自定义型):
 
 
d
3)      first sleep 语句被注释,而 second/third sleep 语句不注释,则 stop 会在两个子进程中被调用。上面程序的写法中 stop 不会被执行。
      声明:本篇及其后续是我的学习笔记,资料来自网络与书本,本人对其中的程序不声明任何版权。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值