实验要求:编写一个多进程并发执行程序。父进程首先创建一个执行 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;
}
来源:oschina
链接:https://my.oschina.net/u/250255/blog/123405