0

I have small project for practice in system calls. The idea is to create a Rock paper scissors game. The controller need to create two child processes and when two processes are created they are supposed to send ready command to the controller (parent process) using SIGUSR1 signal. I have created the two children processes and the signal sent the signal to the controller but the problem message does not print out. what am I wrong?

Here is my code.

#include<stdio.h>
#include<unistd.h> // fork(); for creating processes and pipe()s
#include<signal.h>  
#include<sys/signal.h> 
#include<stdlib.h> 

 void handle_sigusr1(int sig){
    
      printf("Sending ready command...\n");
    
   }
   
   int x = 0;
int main(int args, char* argv[]){

int player0, player1;

player0 = fork();
if(player0 != 0){

 player1 = fork();

}

if( player0 == 0){
    kill(getppid(), SIGUSR1);
    sleep(2);
    
}else if(player1 == 0){
    sleep(3);
    kill(getppid(), SIGUSR1);
    
}else{
 wait(NULL);
 struct sigaction sa = { 0 };
    sa.sa_flags = SA_RESTART;
    sa.sa_handler = &handle_sigusr1;
    sigaction(SIGUSR1, &sa, NULL);
    
    if(signal(SIGUSR1, handle_sigusr1)){
       x++;
       printf("Controller: Received ready command. Total %d\n", x);
      
    }
}

return 0;
}
Phillips
  • 51
  • 1
  • 7

1 Answers1

0

In your code, there are 2 major issues to modify.

First of all, move the signal handler above the wait() function, otherwise you are defining how to handle the signal after receiving it

signal(SIGUSR1, handle_sigusr1);
wait();

Then, the parent process is waiting for only 1 child to receive the signal. You should add a loop to wait both the child processes in the parent statement branch

Alez
  • 1,913
  • 3
  • 18
  • 22