Ran into some difficulties with a program I'm writing up over the last few days. I simply want a program to run with signals. When a user hits control c, I create two pipes and 1 parent that has two children.
When the user hits control Z from a child process, I want the children to talk to one another. At the time being, I just want it to print out some line to terminal. Now after doing some tests on the problem, I concluded on some factors.
- If the signal for control Z is placed in the parent process (commented out line in the code), the program runs fine...
- If the signal is then moved to the child process....it terminates the program for some reason. I assumed it was the child dying, however using commands such as sleep and wait proved to be ineffective.
Can someone see where I am going wrong...its really starting to bug me :/
#include <stdio.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
pid_t forkA, forkB;
void handleSignal();
void controlC();
void controlZ();
int main ()
{
signal(SIGINT, handleSignal);
while(1);
}
void handleSignal (int signal)
{
if (signal == SIGINT)
{
write(1, "ContrlC \n", 11);
controlC();
}
else if (signal == SIGTSTP)
{
write(1, "CONTROLZ \n", 11);
controlZ();
}
else
{
write(2, "error \n", 8);
}
}
void controlC()
{
int firstPipe[2];
int secondPipe[2];
if (pipe(firstPipe) < 0)
{
write(1,"Error \n", 7);
}
else if (pipe(secondPipe) < 0)
{
write(1,"Error creating pipe 2 \n", 23);
}
else
{
write(1, "Pipe creations: DONE \n", 22);
}
//make child
forkA = fork();
if (forkA < 0)
{
write(2, "FORK ERROR. \n", 13);
}
else if (forkA == 0)
{
write(1, "CHILD 1 \n", 9);
close(firstPipe[0]); //close reading end of pipe 1
close(secondPipe[1]);//close writing end of pipe 2
sleep(5);
}
else
{
forkB = fork();
if (forkB < 0)
{
write(2, "FORK ERROR. \n", 12);
}
else if (forkB == 0)
{
signal(SIGTSTP, handleSignal);
write(1, "CHild 2 \n", 9);
close(firstPipe[1]); //close write end of pipe 1
close(secondPipe[0]); //close read end of pipe 2
sleep(5);
}
else
{
//signal(SIGTSTP, handleSignal);
signal(SIGCHLD, SIG_IGN);
write(1,"parent of both \n", 16);
wait();
}
}
}
void controlZ()
{
write(1, "woo z \n", 7);
}