SugarMouse SugarMouse - 1 year ago 108
C Question

Is there a good way to alter execution order of child processes created with fork()?

I am looking for creating child processes for which I can control their order of processing.

Simple example:


  • Parent creates 2 children with fork

  • Children


    1. First child prints "Message 2"

    2. Second child prints "Message 1"


  • When this is finished parent prints "End"



Because of the fact that we can't know for sure which process will be executed first, there are high chances that the final result would be:


Message 2

Message 1

End


I am trying to make sure that the second child executes the print before the first child and that the parent executes its print after all the children.

For the parent it's quite easy with the wait()/waitpid() functions. However it seems harder with the children.

Here is an implementation of my ideas to achieve the objective:

(note: I'm still quite new to the creation of child processes and I may have misunderstood things in this implementation)

#include <stdlib.h>
#include <stdio.h>

#include <sys/types.h>
#include <signal.h>
#include <unistd.h>

static int init = 0;

void setInitFinished(int sig)
{
if (sig == SIGUSR1)
init = 1;
}

int main()
{
signal(SIGUSR1, setInitFinished);

pid_t pid1, pid2;
int status1, status2;

// CHILD 1
if (!(pid1 = fork()))
{
while (!init); // Waiting all children to be initiated

// Once all children created, we wait for child 2 to print its message
int pidOfChild2 = getpid()+1; // I checked, the PID is correct
waitpid(pidOfChild2, &status1, 0);

printf("MESSAGE 2\n");
exit(0);
}

// CHILD 2
if (!(pid2 = fork()))
{
while (!init); // Waiting all children to be initiated

// No need to wait since it's the first message to be printed
printf("MESSAGE 1\n");
exit(0);
}

// PARENT

// All children have been created, tell it to all the children
kill(pid2,SIGUSR1);
kill(pid1,SIGUSR1);

// When every child has finished its work, continue parent process
waitpid(pid1, &status1, 0);
waitpid(pid2, &status2, 0);

printf("Parent end\n");

return 0;
}


In the child 1 I am trying to wait for the Child 2 with waitpid(pidOfChild2, ...); but it doesn't seem to work.

I'm still discovering the fork functionalities so I'm pretty sure to misunderstand a lot of things here.

NB: I want to avoid using sleep(), it could work but it's not pretty

Answer Source

You need to use actual inter-process communication to achieve this.

You seem to think that the waitpid() function has something to do with waiting for a process to print output, but that's not at all what it does.

Create a semaphore in the parent, pass it to both children, and have one child wait on the semaphore before printing and the other one messaging the semaphore after it's done printing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download