forked from wadehuber/codeexamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfork.c
More file actions
51 lines (44 loc) · 1.08 KB
/
Copy pathfork.c
File metadata and controls
51 lines (44 loc) · 1.08 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int n = 0;
int pid;
pid_t childwait;
printf("Before fork: n=%d\n", n);
sleep(1);
/* fork the process
returns child PID to the parent process
return 0 to the child process
*/
pid = fork();
/* Child process */
if (pid == 0) {
n = 1;
printf("\t\t\t\tChild process:\n");
printf("\t\t\t\t n=%d, PID=%d\n", n, pid);
while (n < 10) {
printf("\t\t\t\t n=%d\n", n);
n++;
sleep(1);
}
printf("\t\t\t\tChild complete..\n");
}
/* Parent process */
else {
printf("\tParent process:\n");
printf("\t n=%d, PID=%d\n", n, pid);
while (n <= 50) {
printf("\t n=%d\n", n);
n += 10;
sleep(1);
}
printf("\tParent: waiting for child.\n");
wait(&childwait);
printf("\tParent: child complete.\n");
printf("\tParent: complete.\n");
}
sleep(2);
exit(0);
}