i am writing a Unix program where a father process forks a child p1.the father process handle the SIGUSR1.
the child process every 1 sec generate a random number between 1 to 9 and send to father using pipe the father Receives the number and print it to the console.when the father process catch the SIGUSR1 signal he begin to print only odd numbers and when the received number is 11 he kill the child by sending SIGTERM signal. the father wait on status and then terminate the child.
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#define READ_END 0
#define WRITE_END 1
volatile sig_atomic_t token;
void handle_me(int signum)
{
token=0;
}
int main(int argc, char *argv[]){
pid_t child1;
token=1;
int pipe1[2],status;
unsigned int bufChild1,bufChild2;
if (pipe(pipe1) == -1)
{
fprintf(stderr, "Pipe failed");
}
child1 = fork();
if (child1 < 0)
{
fprintf(stderr, "Fork Failed");
return 0;
}
else if (child1 == 0)
{
printf(" child with pid %d\n", getpid());
printf("The Parent pid is %d\n", getppid());
while(1)
{
bufChild1 = (unsigned int)rand()%9 +1;
fprintf(stdout, "generated: %u\n", bufChild1);
close(pipe1[READ_END]);
write(pipe1[WRITE_END],&bufChild1,sizeof(bufChild1)); //write into the Parent
close(pipe1[WRITE_END]);
}
}
else
{
signal(SIGUSR1,handle_me);
printf(" Parent Process\n");
while(!token)
{
close(pipe1[READ_END]);
read(pipe1[READ_END],&bufChild2,sizeof(bufChild2)); //write into the Parent
fprintf(stdout, "Received: %u\n", bufChild2);
close(pipe1[WRITE_END]);
}
}
wait(&status);
return 1;
}
i wonder how to implement this condition when the father process catch the SIGUSR1 signal he begin to print only odd numbers and when the recieved number is 11 he kill the child by sending sigterm signal.
I Used a global variable Which can be set if SIGUSR1 is caught by the father.
i will be very thankful if someone can help me.