I have a problem sending multiple signals to parent process in c. I've been trying for a long time now and I still end up in a deadlock or a waitlock. But I think it shouldn't be that complicated, I simply can't understand what is going on..
So I have a parent process and two child processes. The children are signaling to the parent, it accepts them, then sends a message to the children in pipe. They write it out to console.
My code so far:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
void handler(int signumber) {
printf("Signal with number %i has arrived\n", signumber);
}
int main() {
signal(SIGUSR1, handler);
signal(SIGUSR2, handler);
int pipefd[2];
char sz[100];
if (pipe(pipefd) == -1)
{
perror("Pipe open error");
exit(EXIT_FAILURE);
}
pid_t child, child2;
child = fork();
if (child > 0)
{
pause();
printf("Signal1 arrived\n", SIGUSR1);
//pause();
printf("Signal2 arrived\n", SIGUSR2);
close(pipefd[0]); //Usually we close unused read end
write(pipefd[1], "Message", 13);
printf("Pipe write complete\n");
int status;
waitpid(child2, &status, 0);
waitpid(child, &status, 0);
printf("Parent process ended\n");
}
else
{
child2 = fork();
if(child2>0) //child 1
{
printf(" child 1 Waits 3 seconds, then send a SIGTERM %i signal\n", SIGUSR1);
sleep(3);
signal(SIGUSR1, handler);
close(pipefd[1]); //Usually we close the unused write end
printf("Child1 read start\n");
read(pipefd[0], sz, sizeof(sz)); // reading max 100 chars
printf("Child1 read end, Message: %s", sz);
printf("\n");
close(pipefd[0]); // finally we close the used read end
printf("Child1 process ended\n");
kill(child, SIGTERM);
}
else //child 2
{
printf("child 2 Waits 3 seconds, then send a SIGTERM %i signal\n", SIGUSR2);
sleep(3);
signal(SIGUSR2, handler);
close(pipefd[1]); //Usually we close the unused write end
printf("Child2 read start\n");
read(pipefd[0], sz, sizeof(sz)); // reading max 100 chars
printf("Child2 read end, Message: %s", sz);
printf("\n");
close(pipefd[0]); // finally we close the used read end
printf("Child2 process ended\n");
kill(child2, SIGTERM);
}
}
return 0;
}```