#一个多进程并发执行的程序。父进程首先创建一个执行ls命令的子进程然后再创建一个执行ps命令的子进程,并控制 ps 命令总在 ls 命令之前执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#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 status_1,status_2;
signal(SIGINT,(sighandler_t)sigcat);//Registe a interrupt fuction
char *args1[]= {"/bin/ls","-a",NULL}; //两个进程
char *args2[]= {"/bin/ps","-a",NULL};
int pid1=fork();
if(pid1<0)
{
printf("Create Process fail\n");
}
if(pid1==0)
{
printf("ls -the child process starting%d\n",getpid());
pause();//Wait for the interrupt
printf("ls the child process waking%d\n",getpid());
status_1=execve(args1[0],args1,NULL);
exit(0);

}
else
{
//Father process
printf("\n Father Process starting%d\n ",getpid());
int pid2=fork();
if(pid2>0)
{

printf("ls the childprocess pause%d\n",pid1);
waitpid(pid2,&status_2,0);
printf("pid2 is over");
printf("ls waking%d\n",pid1);
kill(pid1,SIGINT);//运行p1
waitpid(pid1,&status_1,0);
printf("ls over%d\n",pid1);
printf("Father process over%d\n",getpid());
exit(0);

}
if(pid2<0)
{
printf("Process 2fails\n");
}
if(pid2==0)
{
printf("ps starting%d\n ",getpid());
status_2=execve(args2[0],args2,NULL);
exit(0);
}

}
return 0;
}