C 睡眠导致水管破裂?

C 睡眠导致水管破裂?,c,linux,posix,C,Linux,Posix,所以在大学里,我现在学习并发编程。我正在做关于管道的练习,并有以下内容: 编写一个程序,创建10个子进程来玩游戏“赢得管道!”必须只有一个管道,由所有进程共享。游戏规则如下:父进程每2秒填充一个结构,其中包含消息“Win”和回合数(1到10),并将该数据写入管道中;每个子进程都试图从管道中读取数据。成功的子级应打印获胜消息和回合号,以等于获胜回合号的退出值结束执行;其余子进程继续尝试从管道读取数据;所有子进程终止后,父进程应打印PID和每个子进程的获胜回合 我有以下代码: #include &l

所以在大学里,我现在学习并发编程。我正在做关于管道的练习,并有以下内容:

编写一个程序,创建10个子进程来玩游戏“赢得管道!”必须只有一个管道,由所有进程共享。游戏规则如下:父进程每2秒填充一个结构,其中包含消息“Win”和回合数(1到10),并将该数据写入管道中;每个子进程都试图从管道中读取数据。成功的子级应打印获胜消息和回合号,以等于获胜回合号的退出值结束执行;其余子进程继续尝试从管道读取数据;所有子进程终止后,父进程应打印PID和每个子进程的获胜回合

我有以下代码:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

struct Something {
    char message[4];
    char round;
};

int main() {
    int fd[2];
    pid_t pid;
    struct Something something;
    int status;

    if (pipe(fd) == -1) {
        perror("error creating pipe");
        return 1;
    }

    for (int i = 0; i < 10; ++i) {
        pid = fork();
        if (pid == 0) { break; }
    }

    if (pid > 0) { //parent
        close(fd[0]);
        while (something.round <= 10) {
            //sleep(2);  PROBLEM HERE
            strcpy(something.message, "Win");
            something.round++;
            write(fd[1], &something, sizeof(something));
        }
        close(fd[1]);
        for (int i = 0; i < 10; ++i) {
            pid = wait(&status);
            printf("PID: %d  won round %d\n", pid, WEXITSTATUS(status));
        }
    } else { //child
        close(fd[1]);
        read(fd[0], &something, sizeof(something));
        close(fd[0]);
        printf("%s %d", something.message, something.round);
        _exit(something.round);
    }

    return 0;
}
#包括
#包括
#包括
#包括
构造某物{
字符消息[4];
焦圆;
};
int main(){
int-fd[2];
pid_t pid;
构造某物;
智力状态;
如果(管道(fd)=-1){
perror(“创建管道时出错”);
返回1;
}
对于(int i=0;i<10;++i){
pid=fork();
如果(pid==0){break;}
}
如果(pid>0){//parent
关闭(fd[0]);

然而(something.round问题在你的循环中

  while (something.round <= 10) {
            //sleep(2);  PROBLEM HERE
            strcpy(something.message, "Win");
            something.round++;

while(something.round
while(something.round请尝试在子项的输出末尾打印一个换行符。@Barmar是的,但它实际上假定值为0,并且仍按预期工作。这可能不是一个好的做法,但我认为我可以将其留给练习。绝对不是,您应该始终初始化变量。
stdout
在写入时是行缓冲的终点站。