Reputation: 1
I have written following code for a simple 3 player game in C.
Flow:
1) Ask user for winning score
2) 3 children are generated
3) Each will generate random scores and accumulate it
4) Whoever reaches winning score wins and terminates the program.
void sigHandler(){}
void player(char *, int *, int *, int);
int main(int argc, char *argv[])
{
int fd1[2], fd2[2], fd3[2], fd4[2], fd5[2], fd6[2], win;
char turn='T';
write(1, "This is a 3 player game with a Referee\n", 38);
printf("Enter the winning score:\n");
scanf("%d", &win);
pipe(fd1);
pipe(fd2);
if(!fork())
player("TOTO", fd1, fd2, win);
sleep(1);
close(fd1[0]);
close(fd2[1]);
pipe(fd3);
pipe(fd4);
if(!fork())
player("TITI", fd3, fd4, win);
sleep(1);
close(fd3[0]);
close(fd4[1]);
pipe(fd5);
pipe(fd6);
if(!fork())
player("TUTU", fd5, fd6, win);
sleep(1);
close(fd5[0]);
close(fd6[1]);
while(1)
{
signal(SIGINT, sigHandler);
signal(SIGSTOP, sigHandler);
write(1,"\nRefree: TOTO plays\n\n", 21);
write(fd1[1], &turn, 1);
read(fd2[0], &turn, 1);
write(1,"\nRefree: TITI plays\n\n", 21);
write(fd3[1], &turn, 1);
read(fd4[0], &turn, 1);
write(1,"\nRefree: TUTU plays\n\n", 21);
write(fd5[1], &turn, 1);
read(fd6[0], &turn, 1);
}
}
void player(char *s, int *fd1, int *fd2, int win)
{
int points=0, dice;
char turn;
srand(time(NULL));
while(1)
{
signal(SIGINT, sigHandler);
signal(SIGSTOP, sigHandler);
read(fd1[0], &turn, 1);
printf("%s: Playing my dice\n",s);
dice =rand() % 20 + 1;
printf("%s: got %d points\n", s, dice);
points+=dice;
printf("%s: Total so far %d\n\n", s, points);
if(points>=win)
{
printf("%s: GAME OVER. I WON.\n", s);
kill(0, SIGTERM);
}
sleep(3);
write(fd2[1], &turn, 1);
}
}
The issue is I am trying to block CTRL+Z and CTRL+C signals when the program is executing but it's not working when I use following code blocks:
signal(SIGINT, sigHandler);
signal(SIGSTOP, sigHandler);
Please provide some suggestions.
Upvotes: 0
Views: 1021
Reputation: 101
Just to add something up to @Thomas's answer I'll just provide you a link that I myself found useful when working with signals.
https://www.usna.edu/Users/cs/aviv/classes/ic221/s16/lec/19/lec.html
P.S: As Thomas aforementioned it's a really neat and classy idea to use SIG_IGN instead of "dummy" signal handlers.
Upvotes: 0
Reputation: 54525
Better than a dummy handler is using the predefined SIG_IGN
(ignore):
signal(SIGINT, SIG_IGN); /* ignore Terminal interrupt signal */
signal(SIGTSTP, SIG_IGN); /* ignore Terminal stop signal */
Further reading:
If the value of func is SIG_IGN, the signal shall be ignored.
Upvotes: 1