-
-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathfork.c
34 lines (31 loc) · 720 Bytes
/
fork.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
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
static void child()
{
printf("I'm child! my pid is %d.\n", getpid());
exit(EXIT_SUCCESS);
}
static void parent(pid_t pid_c)
{
printf("I'm parent! my pid is %d and the pid of my child is %d.\n",
getpid(), pid_c);
exit(EXIT_SUCCESS);
}
int main(void)
{
pid_t ret;
ret = fork();
if (ret == -1)
err(EXIT_FAILURE, "fork() failed");
if (ret == 0) {
// child process came here because fork() returns 0 for child process
child();
} else {
// parent process came here because fork() returns the pid of newly created child process (> 1)
parent(ret);
}
// shouldn't reach here
err(EXIT_FAILURE, "shouldn't reach here");
}