c - C中的进程同步

标签 c process signals fork signal-handling

我正在尝试用 C 语言开发一款 3 人游戏。该程序创建了 3 个 child 和 1 个 parent 。 parent 打印并休眠并向相关 child 发送信号。 child 在一些计算后暂停, parent 应该再次醒来。但输出远不及它。我尝试在不同的地方使用 sleep() 但没有成功。有人可以帮帮我吗

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

最佳答案

你的括号放错地方了。你写道:

if((pid1=fork()==0)) child("TOTO");

应该是:

if((pid1=fork())==0) child("TOTO");

在您的情况下,您将 0 分配给父进程中的 pid1pid2pid3,并在子进程中分配 1子进程,因为 fork()==0 在赋值运算符 = 之前求值。

我建议不要在表达式中使用带有副作用的操作(尽管我知道在这种情况下这是常见的做法)。毕竟,如果您多花一行,就可以完全避免这个问题:

pid1 = fork();
if (pid1 == 0) child("TOTO");

有副作用的操作,例如=+=*=++-- 等作为单独的语句使用时是最安全的。在其他表达式中,它们的含义可能不清楚甚至未定义。在以下语句中:

x = x++ + 1;

增量 ++ 可以在 = 评估之前或之后应用。如果 x = 0 最初,x 之后可能是 1 或 2。

关于c - C中的进程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35974321/

相关文章:

c++ - 是否有最常见的有害命令列表?

c - 如何使用 fscanf 读取以分号分隔的行

c - 使用几个线程使用 WINAPI

image - 如何在 Windows 上暂停和恢复应用程序?

C子进程没有收到SIGINT信号

python - 我可以在 Django 中手动触发信号吗?

c - Udp readfrom直到结束

c - 在C中通过地址传递struct-within-pointer-array-within-struct

java - ProcessBuilder 找不到指定的文件,而 Process 可以

c - shmget 不工作