Sleep()导致管道破裂?

问题描述 投票:0回答:1

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

编写一个程序,该程序创建10个子进程来玩“ Win the pipe!”游戏。 必须只有一个管道,所有进程都共享。游戏的规则如下:父进程每2秒填充一个结构,其中显示消息“胜利”和回合编号(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;
}

所以当我没有对sleep()进行注释并运行该程序时,将发生冻结并且不打印任何内容,子进程将一步一步缓慢完成的情况,然后我将收到断线消息。

但是当我注释sleep()时,程序运行得很好,父母不等待2秒钟,只是填满了我想的管道。我无法理解此问题,并且一直未找到答案。

如果我能对此有所启发,我会很感激。

c linux posix
1个回答
0
投票
while (something.round <= 10) { //sleep(2); PROBLEM HERE strcpy(something.message, "Win"); something.round++;

将迭代11次。

尝试something.round < 10
© www.soinside.com 2019 - 2024. All rights reserved.