我想用C语言开发3人游戏。该程序创建3个孩子和1个父母。家长打印并进入睡眠状态并向相关的孩子发送信号。小孩经过一些计算后会暂停,家长应该再次醒来。但是输出远没有接近它。我尝试在各个地方使用sleep(),但没有运气。是否有人可以帮助我走出C中的进程同步
void action(){}
void child(char *);
int main(int argc, char *argv[])
{
pid_t pid1,pid2, pid3;
printf("This is a 3 player game\n");
if((pid1=fork()==0)) child("TOTO");
if((pid2=fork()==0)) child("TITI");
if((pid3=fork()==0)) child("TUTU");
sleep(1);
signal(SIGUSR1, action);
while(1)
{
printf("\nRefree: TOTO Plays\n\n");
kill(pid1,SIGUSR1);
pause();
printf("\nRefree: TITI Plays\n\n");
kill(pid2,SIGUSR1);
pause();
printf("\nRefree: TUTU Plays\n\n");
kill(pid3, SIGUSR1);
pause();
}
}
void child(char *s)
{
int points=0,dice;
while(1)
{
signal(SIGUSR1, action);
pause();
printf("\n%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(2);
if(points >= 50)
{
printf("%s: game over I won\n", s);
kill(0, SIGTERM);
}
kill(getppid(), SIGUSR1);
}
}
输出我得到的是
This is a 3 player game
Refree: TOTO Plays
TITI: Playing my dice
TUTU: Playing my dice
TOTO: Playing my dice
TUTU: got 4 points
TOTO: got 4 points
TOTO: Total so far 4
TITI: got 4 points
TUTU: Total so far 4
TITI: Total so far 4
User defined signal 1
与'x ++'很好的搭配..这实际上意味着代码会导致未定义的行为。 –