Reputation: 11
I need two child processes to do this:
printf
even numbers between 0 and 100.printf
odd numbers between 0 and 100.What I should see in terminal after execution is: 0 1 2 4..100
How can I do this?
I tried this program, but it doesn't work, it only gives me the first integer 0:
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
void handler1(int sig)
{
if(sig == SIGCONT)
{
raise(SIGCONT);
}
}
void handler2(int sig)
{
if(sig == SIGCONT)
{
raise(SIGCONT);
}
}
int main()
{
int i=-1;
if(fork()==0)
{
signal(SIGCONT,handler1);
while(1)
{
printf("%d\n",i+1);
pause();
kill(getpid()+1,SIGCONT);
}
}
if(fork()==0)
{
signal(SIGCONT,handler2);
while(1)
{
pause();
printf("%d\n",i+1);
kill(getpid()-1,SIGCONT);
}
}
}
Upvotes: 1
Views: 686
Reputation: 2412
Signals are not a good solution for this problem. The first signal gets lost (it is sent by the first child before the second child starts), and you end up locked (because one of the processes is waiting for a signal that it had already missed).
Try using semaphores or message queues instead. They are immune to this problem, because they don't get lost in the system, even when not all processes involved are already started.
Upvotes: 2