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
- First child prints "Message 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
");
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
");
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
");
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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…