使用信号的三人C游戏
我一直在尝试用C语言开发一个3人游戏,使用信号,但它并没有给出期望的输出使用信号的三人C游戏,c,unix,parallel-processing,signals,signal-handling,C,Unix,Parallel Processing,Signals,Signal Handling,我一直在尝试用C语言开发一个3人游戏,使用信号,但它并没有给出期望的输出 #define _POSIX_SOURCE //to use functionality from the POSIX.1 standard as ANCI C does not support kill() #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #
#define _POSIX_SOURCE //to use functionality from the POSIX.1 standard as ANCI C does not support kill()
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <signal.h>
#include <fcntl.h>
#include <time.h>
void action(){}
void child(char *);
int main(){
pid_t pid1, pid2, pid3;
printf("This is a 3-players game with a referee\n\n");
if((pid1=fork()) == 0) child("TOTO");
sleep(1);
if((pid2=fork()) == 0) child("TITI");
sleep(1);
if((pid3=fork()) == 0) child("TUTU");
sleep(1);
while(1){
signal(SIGUSR1, action);
printf("Refree: TOTO plays\n\n");
kill(pid1, SIGUSR1);
pause();
printf("Refree: TITI plays\n\n");
kill(pid2, SIGUSR1);
pause();
printf("Refree: TUTU plays\n\n");
kill(pid3, SIGUSR1);
pause();
}
}
void child(char *s){
int points=0, dice;
srand(time(NULL));
while(1){
signal(SIGUSR1, action); // block myself
pause();
sleep(1);
printf("%s: playing my dice\n", s);
dice = rand() % 10 + 1;
printf("%s: got %d points\n", s, dice);
points+=dice;
printf("%s: Total so far %d\n\n", s, points);
sleep(3);
if(points >= 100){
printf("%s: game over I won\n", s);
kill(0, SIGTERM);
}
kill(getppid(), SIGUSR1);
}
}
它从不显示“图图”玩骰子,并使用注册为空白信号的用户定义信号1终止。只有在玩家获胜后,程序才会终止
有什么建议吗?当裁判接到托托的信号时,它的处理被重置为
SIG\u DFL
,所以提提的信号真的杀死了他。裁判员必须在每次kill()
之前,在每个循环中呼叫信号(SIGUSR1,动作)
三次
另一种选择是#定义#BSD_源
(仔细阅读man 2 signal
的可移植性部分),它强加了一种BSD语义,即不重置刚添加的#定义#BSD_源,现在它就像一个符咒一样工作。
This is a 3-players game with a referee
Refree: TOTO plays
TOTO: playing my dice
TOTO: got 8 points
TOTO: Total so far 8
Refree: TITI plays
TITI: playing my dice
TITI: got 2 points
TITI: Total so far 2
User defined signal 1