Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit a child process after forking

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 _exit, 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.

like image 944
TrevTS Avatar asked Sep 15 '15 22:09

TrevTS


People also ask

How do I get out of child process?

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.

What is the most appropriate action to do in a child process after a successfully fork?

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.

What does exit do in fork?

I am the parent, the child is 16959. exit() closes all files and sockets, frees all memory and then terminates the process.

What happens when you fork a child 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.


2 Answers

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
}
like image 112
blaze Avatar answered Nov 09 '22 03:11

blaze


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.

like image 31
John Kugelman Avatar answered Nov 09 '22 03:11

John Kugelman