I am looking for creating child processes for which I can control their order of processing.
Simple example:
Message 2
Message 1
End
#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;
}
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.