子进程和父进程之间的交互情况主要有如下(不涉及信号):
case1: 父进程不管子进程,自顾运行;
case2: 父进程等待子进程结束后,再运行;
case3: 父进程同时创建多个子进程,等待所有子进程结束后,再运行;
上述的三种情况,第一种基本情况此处不考虑;
对于case2:
父与子的等待,其实也就涉及到两者的通信;两者的通信主要通过wait()和exit()完成;
父通过wait()阻塞,等待子进程结束;
子进程通过exit()唤醒父进行,并且结束自己的运行;如果没有调用exit(),子进程会继续执行下去;
父进程如果希望知道子进程的退出时状态,可以带参数的wait(&stat);
具体的代码如下:
/*
*this program is to test the comm. between parent and child proess.
* the parent uses fork() to create a child process;
* the parent uses wait() to block and wait for the child;
* the child invokes exit() to wake up parent;
*
* as child can exit with different status, so how does the
* parent knows for what the child exits.
*
* The parent knows the exist status of the child as follows:
* wait(&stat);
*
* when exit(n) is called in child, varible 'stat' is splited into three parts:
* |exit number|core dump flag|signal number|
* exit num: 8 bits;
* core dump flag: 1 bit;
* signal number: 7 bits;
*
* this explains: high_8 = stat >> 8;
*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int stat = 0;
printf("i am parent pid=%d\n", getpid());
if(fork() == 0)
{
printf("i am child pid=%d\n", getpid());
sleep(3);
printf("work done in child\n");
exit(17); //without exit, the child executes through;
}
//wait(NULL);
wait(&stat);
int high_8 = stat>>8;
printf("stat=%d, parent conitnue...\n", high_8);
return 0;
}
对于case3:
父进程负责创建输入指定数量的n个进程,每个进程干的事情很简单,就是sleep特定的秒数,
当每个进程结束时,由父进程来报告相应子进程的结束状况;
/*
* this program is to create the number of child processes as you specified.
* for(i=0; i<n; i++)
* newpid = fork(); //does not work, because the child process also invokes fork();
*
*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int stat = 0;
int newpid;
int count = 0;
int i;
int n;
printf("i am parent pid=%d\n", getpid());
printf("please input the number of child processes:\n");
scanf("%d", &n);
while((newpid=fork()) != 0){
count++;
if(count == n)
break;
}
if(newpid == 0){
printf("i am child pid=%d\n", getpid());
sleep(3);
exit(2);
}
for(i=0; i<n; i++)
{
newpid=wait(&stat);
printf("child=%d done\n", newpid);
}
printf("parent process continue...\n");
return 0;
}