一个多进程并发执行程序ps命令 ls命令

实验要求:编写一个多进程并发执行程序。父进程首先创建一个执行 ls 命令的子进程然//后再创建一个执行ps 命令的子进程,并控制ps 命令总在 ls 命令之前执行。
//Copyright:(C) 2013.4 By ZhengDujin
//Linux Ubuntu12.04 Gcc Vim
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
typedef void (*sighandler_t)(int);
void sigcat(){
printf("Coming back to the process %d.\n",getpid());
}
int main(){
int status;//存放子进程返回状态
pid_t pls,pps;//存放子进程号
signal(SIGINT,(sighandler_t)sigcat);//注册一个本进程处理键盘中断的函数
char *args1[]={"/bin/ls","-a",NULL};
char *args2[]={"/bin/ps","-l",NULL};
pls=fork();//创建子进程运行命令 /bin/ls
//printf("Process %d is created which for /bin/ls.\n",getpid());
if(pls<0){
    printf("Error ocurrs while creating new process.\n");
    exit(EXIT_FAILURE);
}
else if(pls==0){//子进程代码段
    printf("Process %d is waiting for /bin/ps running.\n",getpid());
    pause();//暂停,接收SIGINT信号后继续执行
    printf("/bin/ls is going to be run in process %d.\n",getpid());
    status=execve(args1[0],args1,NULL);//装入并执行新程序
    printf("Error ocurrs while running /bin/ls.\n");
    exit(EXIT_FAILURE);
}
else{
    pps=fork();//创建子进程运行命令 /bin/ps
   // printf("Process %d is created which for /bin/ps.\n",getpid());
    if(pps<0){
      printf("Error ocurrs while creating new process:Abort\n");
      exit(EXIT_FAILURE);
    }
    else if(pps==0){
      printf("Process %d is going to run /bin/ps.\n",getpid());
      status=execve(args2[0],args2,NULL);//装入并执行新程序
      printf("Error ocurrs while running /bin/ps.\n");
      exit(EXIT_FAILURE);
    }
    else{
      waitpid(pps,&status,0);
      printf("Sending signal to Process %d.\n",pls);
      if(kill(pls,SIGINT)<0){//发送SIGINT信号使进程继续运行命令 /bin/ls.
        printf("Error ocurrs while sending a signal to a child process.\n");
        exit(EXIT_FAILURE);
      }
      waitpid(pls,&status,0);
    }
}
return 0;
}


转载于:https://my.oschina.net/u/250255/blog/123405

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值