实验内容:
编写⼀个多进程并发执⾏程序。⽗进程建⽴两个⼦进程,⾸先创建的让其执⾏ ls 命令,之后创建执⾏让其执⾏ ps 命令,并控制 ps 命令总在 ls 命令之前执⾏。要求⽗进程等待两个⼦进程结束。
#include <sys/types.h>
#include <wait.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h> // 进程⾃定义的键盘中断信号处理函数
typedef void (*sighandler_t) (int);
void sigcat() {
printf("%d Process continue\n", getpid());
}
int main(int argc,char *argv[])
{
int i;
int pid,pid2; int status;
char *args[] = {"/bin/ls", "-a", NULL};
char *args2[] = {"/bin/ps", "-a", NULL};
signal(SIGINT,(sighandler_t)sigcat); pid=fork();
if(pid<0)
{
printf("create process faild!\n"); exit(EXIT_FAILURE);
}
if(pid==0)
{
printf("I am Child1 process %d, my Father is %d\n", getpid(), getppid()); pause();
printf("Child1 %d is Running: \n", getpid());
printf("%s ", args[0]); printf("\n"); status=execve(args[0],args,NULL);
return 0;
}
pid2=fork();
if(pid2<0)
{
printf("create process faild!\n"); exit(EXIT_FAILURE);
}
if(pid2==0)
{
printf("I am Child2 process %d, my Father is %d\n", getpid(), getppid());
printf("%s ", args2[0]); printf("\n"); status=execve(args2[0],args2,NULL);
//return 0;
}
printf("I am Parent process %d\n", getpid());
printf("Parent %d is Waiting for Child2 done\n\n", getpid());
waitpid(pid2, &status, 0);
//先等待子进程二退出之后,再唤醒子进程一
printf("\nParent %d Wakeup Child1 %d\n", getpid(), pid);
kill(pid,SIGINT);
printf("Parent %d is Waiting for Child1 done\n\n", getpid());
waitpid(pid, &status, 0);
printf("\nMy Child Exit with status = %d\n\n", status);
return 0;
}