-
Notifications
You must be signed in to change notification settings - Fork 1
/
Family_Of_processes_AsTree.cpp
68 lines (60 loc) · 1.35 KB
/
Family_Of_processes_AsTree.cpp
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
67
68
// CPP code to create three child
// process of a parent
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// Driver code
int main()
{
int pid, pid1, pid2;
// variable pid will store the
// value returned from fork() system call
pid = fork();
// If fork() returns zero then it
// means it is child process.
if (pid == 0)
{
// First child needs to be printed
// later hence this process is made
// to sleep for 3 seconds.
sleep(3);
// This is first child process
// getpid() gives the process
// id and getppid() gives the
// parent id of that process.
printf("child[1] --> pid = %d and ppid = %d\n",
getpid(), getppid());
}
else
{
pid1 = fork();
if (pid1 == 0)
{
sleep(2);
printf("child[2] --> pid = %d and ppid = %d\n",
getpid(), getppid());
}
else
{
pid2 = fork();
if (pid2 == 0)
{
// This is third child which is
// needed to be printed first.
printf("child[3] --> pid = %d and ppid = %d\n",
getpid(), getppid());
}
// If value returned from fork()
// in not zero and >0 that means
// this is parent process.
else
{
// This is asked to be printed at last
// hence made to sleep for 3 seconds.
sleep(3);
printf("parent --> pid = %d\n", getpid());
}
}
}
return 0;
}