According to the task, the program must create a copy of itself using fork () to process the task. Parent process must not be blocked while the child is running.
However, I encountered strange behavior of the test program. According to the result of pgrep, child processes are not terminated until the parent program has completed its execution. Each time fork() is called, pgrep shows that the number of processes is increasing, but they are not terminating.
I wrote a simple program that runs for nearly 35 seconds and spawns a child process 3 times, which should exit after 5 seconds:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
for (int i = 1; i < 36; i++) {
if (i % 10 == 0) {
pid_t forkrank = fork();
if (forkrank == 0) {
printf("forked process starts\n");
sleep(5);
return 1;
}
}
sleep(1);
}
return 0;
}
But during its execution, pgrep shows that running processes are not terminated until parent ends:
But if I add a blocking code to wait for the result of the child process execution, then additional processes are terminated correctly:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char* argv[])
{
for (int i = 1; i < 36; i++) {
if (i % 10 == 0) {
pid_t forkrank = fork();
if (forkrank == 0) {
printf("forked process starts\n");
sleep(5);
return 1;
}
int wstatus;
waitpid(forkrank, &wstatus, 0);
int retValue = WEXITSTATUS(wstatus);
}
sleep(1);
}
return 0;
}
pgrep:
Why is this happening? How to terminate child processes without blocking the main one?