Search code examples
cipcforkparent-child

how to create two processes from a single Parent


I know I'm going to need to use fork(), but this just creates a single child process. Do i simply call fork again from within the child process? Also, I need them to communicate through a signal or pipe, which is easier to implement and what do i need to know for doing that (functions, etc..)


Solution

  • To create a second process, call fork() again - either within the parent or the child (but not both!). Which you choose depends on whether you want this process to be a child of the original parent or a child of the first child process (it is usual for it to be a child of the original parent).

    Communicating through a pipe is much simpler and more reliable than using signals. pipe(), close(), read(), write() and select() are the key functions here.


    For example, to have the parent create two child processes, you would do something like:

    pid_t child_a, child_b;
    
    child_a = fork();
    
    if (child_a == 0) {
        /* Child A code */
    } else {
        child_b = fork();
    
        if (child_b == 0) {
            /* Child B code */
        } else {
            /* Parent Code */
        }
    }