Skip to content

Commit 0d4fc77

Browse files
author
mgroot
committed
5.1: Processes | Add 'Zombie-checker' example
1 parent 7ab111f commit 0d4fc77

File tree

2 files changed

+124
-0
lines changed

2 files changed

+124
-0
lines changed
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
#include <iostream>
2+
#include <unistd.h>
3+
#include <sys/wait.h>
4+
#include <signal.h>
5+
#include <random>
6+
7+
#define CHILDS_NUMBER 10
8+
#define WORK_DELAY 2
9+
10+
///////////////// CHILD
11+
12+
int childs_code(int number)
13+
{
14+
/// set deed
15+
std::srand(std::time(NULL)); // set personal seed
16+
sleep(CHILDS_NUMBER - number); // wait for other processes
17+
18+
/// rand
19+
int random_duration = 5 + std::rand() % 20;
20+
std::cout << "\t[" << getpid() << "] is waiting for "
21+
<< random_duration << " seconds" << std::endl;
22+
23+
/// sleep
24+
sleep(random_duration);
25+
26+
/// exit
27+
exit(0);
28+
}
29+
30+
31+
32+
///////////////// FORK
33+
34+
int create_childs()
35+
{
36+
pid_t pid;
37+
38+
std::cout << "Creating child processes..." << std::endl;
39+
for (int i = 0; i < CHILDS_NUMBER; ++i)
40+
{
41+
pid = fork();
42+
if (!pid)
43+
{
44+
childs_code(i);
45+
}
46+
else if (pid < 0)
47+
{
48+
std::cerr << "Fork failed!" << std::endl;
49+
return 1;
50+
}
51+
52+
sleep(1);
53+
}
54+
std::cout << "Creating done...\n" << std::endl;
55+
56+
return 0;
57+
}
58+
59+
60+
61+
62+
///////////////// MAIN PROCESS
63+
//////////// CHECK
64+
65+
bool check_zombies()
66+
{
67+
/// begin
68+
std::cout << "Start zombie checking..." << std::endl;
69+
70+
// wait for processes
71+
int pid, status;
72+
while((pid = waitpid(-1, &status, WNOHANG)) > 0)
73+
{
74+
/* exited process */
75+
std::cout << "\tProcess with PID[" << pid
76+
<< "] exited with status [" << WEXITSTATUS(status)
77+
<< "]" << std::endl;
78+
}
79+
80+
// check last PID
81+
if (pid < 0) /* error or no childs */
82+
{
83+
if (errno != ECHILD)
84+
std::cerr << "Waitpid error : " << ::strerror(errno) << std::endl;
85+
86+
std::cout << "Zombie check has been done. "
87+
"There is no child processes left" << std::endl;
88+
return false;
89+
}
90+
else /* no exited processes */
91+
{
92+
std::cout << "Zombie check has been done. "
93+
"There is still some running child processes." << std::endl;
94+
return true;
95+
}
96+
}
97+
98+
99+
//////////// WORK
100+
101+
void some_work()
102+
{
103+
int counter = 0;
104+
while (counter < CHILDS_NUMBER)
105+
{
106+
std::cout << "\n*Doing some hard work*" << std::endl;
107+
sleep(WORK_DELAY);
108+
109+
if (!check_zombies())
110+
{
111+
std::cout << "\n*Hard work has been done*" << std::endl;
112+
return;
113+
}
114+
}
115+
}
116+
117+
118+
///////////////// MAIN
119+
120+
int main()
121+
{
122+
create_childs();
123+
some_work();
124+
}

0 commit comments

Comments
 (0)