I'm working on some stuff using fork()
in C. This is my first contact with the concept of forking processes.
Basically, I have something like this:
int pid;
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed");
exit(-1);
} else if (pid == 0) {
fprintf(stderr, "Inside child %d\n", getpid());
// do some other stuff
exit(0);
} else {
fprintf(stderr, "Inside parent %d\n", getpid());
}
Before, I hadn't put the exit(0)
in the child process' code. I was getting seemingly tons of duplicate processes. I added the exit(0)
and now I'm only spawning one child. However, I want to know if this is proper practise or just a bandaid. Is this the correct thing to do. How should a child "stop" when its done?
Usually the child either has it's own code with an exit
or calls one of the exec
functions to replace its process's image with another program. So the exit is okay. But the parent and child could execute at least some of the same code, something like this:
int pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed");
exit(-1);
} else if (pid == 0) {
// child code
} else {
// parent code
}
// shared code
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