/
fork7.c
47 lines (40 loc) · 1.3 KB
/
fork7.c
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
/*************************************************************************
> File Name: fork7.c
> Author: hepan
> Mail: hepansos@gmail.com
> Created Time: 2016年07月25日 星期一 16时27分53秒
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
if ((pid = fork()) < 0) {
perror("fork");
} else if (pid == 0) { //first child
if ((pid = fork()) < 0) {
perror("fork");
} else if (pid > 0) {
exit(0); //parent from second fork == first child
}
/*
* We're the second child;our parent becomes init as soon
* as our real parent calls exit() in the statement above.
* Here's where we'd continue executing,knowing that when we're done, init will reap our status.
*/
//sleep(2);
printf("second child,parent pid = %d\n",getpid());
exit(0);
}
if (waitpid(pid,NULL,0) != pid) { //wait for first child
perror("waitpid");
}
/*
* We're the parent (the original process);we continue executing,
* knowing that we're not the parent of the second chilid.
*/
exit(0);
}