I have this code and it's goal is to create N child processes and print out each PID and process number.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void childProcess(int num)
{
pid_t pid = fork();
printf("Hello! I am process no. %d! my PID is %d!\n", num, pid);
}
int main()
{
int i = 0;
for(i = 1; i <= 5; i++)
{
childProcess(i);
_exit(3);
}
exit(0);
}
However after trying multiple ways: e.g exit
vs _exi
t, recursion in childProcess
, pid = wait()
, I am still having trouble creating only 5 processes. With this code so far my output is:
Hello! I am process no. 1! my PID is 96196!
Hello! I am process no. 1! my PID is 0!
I'm not sure how to properly exit from a child process. Without the exit the code creates N! processes.
It is known that fork() system call is used to create a new process which becomes child of the caller process. Upon exit, the child leaves an exit status that should be returned to the parent. So, when the child finishes it becomes a zombie.
Because fork creates a new process, we say that it is called once—by the parent — but returns twice—in the parent and in the child. In the child, we call execlp to execute the command that was read from the standard input. This replaces the child process with the new program file.
I am the parent, the child is 16959. exit() closes all files and sockets, frees all memory and then terminates the process.
When a process calls fork, it is deemed the parent process and the newly created process is its child. After the fork, both processes not only run the same program, but they resume execution as though both had called the system call.
You are correctly exiting child process, it is just that you do it at wrong time. After fork() every child process keeps running same loop as parent, creating another child processes and that's why you end up having a lot of them.
Correct code would be something like this:
for (int i = 0; i < 5; i++) {
if (fork() == 0) {
// child process
printf("I'm child %d, my pid is %d\n", i, getpid());
exit(0);
}
// parent process keeps running the loop
}
fork()
splits your process into two processes, a parent and a child. You need some sort of test of its return value inside childProcess()
to figure out if you're in the parent or the child. If pid
is 0 then you're in the child; if non-zero then you're in the parent. Based on that you'll want to conditionally exit the program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With