I am learning how to use signals in linux. There are 4 child processes and one parent process. My output is supposed to go in these stages:
Parent receives signal from child 1
Parent receives signal from child 2
Parent receives signal from child 3
Parent receives signal from child 4
Init ended
Phase 1 begins
Child 1 receives signal from parent
Child 2 receives signal from parent
Child 3 receives signal from parent
Child 4 receives signal from parent
Parent receives signal from child 1
Parent receives signal from child 2
Parent receives signal from child 3
Parent receives signal from child 4
Phase 1 ends
Phase 2 begins
Child 1 receives signal from parent
Child 2 receives signal from parent
Child 3 receives signal from parent
Child 4 receives signal from parent
I am currently trying to do the part before Phase 1 ends and I am struggling. Here is my code:
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXCP 3
int ccount=0;
void p_action(int sig){
if (sig == SIGUSR2){
printf("\ncontroller(%d): Received signal SIGUSR2 from child process\n",
(int)getpid());
}
--ccount;
}
void c_action(int sig){
if (sig == SIGUSR1){
printf("\ncompute(%d): Received signal SIGUSR1 from parent process %d\n",
(int)getpid(), (int)getppid());
}
exit(0);
}
int main(){
pid_t pid[MAXCP], parent_pid;
//int nprocs = 0;
ccount = MAXCP;
static struct sigaction pact, cact[MAXCP];
pact.sa_handler = p_action;
sigaction(SIGUSR2, &pact, NULL);
int count;
for (count = 0; count < MAXCP; count++){
switch(pid[count] = fork()){
case -1:
perror("Fork error");
exit(1);
case 0:
//sleep(1);
cact[count].sa_handler = c_action;
sigaction(SIGUSR1, &cact[count], NULL);
printf("Sending SIGUSR2 to parent");
kill(getppid(), SIGUSR2);
pause();
break;
default:
pause();
//printf("Parent is sleeping");
while (ccount != MAXCP){
sleep(60);
}
for (ccount = 0; ccount < MAXCP; ccount++)
kill(pid[count], SIGUSR1);
break;
}
}
return 0;
}
My output is such:
// When I use the above code
controller(3132): Received signal SIGUSR2 from child process
// When I comment out the pause in the child section
controller(3140): Received signal SIGUSR2 from child process
Sending SIGUSR2 to parent
controller(3141): Received signal SIGUSR2 from child process
Sending SIGUSR2 to parentSending SIGUSR2 to parentSending SIGUSR2 to parentSending SIGUSR2 to parentSending SIGUSR2 to parent
controller(3142): Received signal SIGUSR2 from child process
^C
Thanks for your time.
--ccount;is undefined, you can only usevolatile sig_atomic_tobjects in signal handlers. In worst case your signal handler modifies the bytes in the middle ofccount != MAXCPor any other use of it, or something equally evil. - Ilja Everilä