Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I be terminating a forked child process with exit()?

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?


1 Answers

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
like image 141
ooga Avatar answered Sep 10 '25 01:09

ooga