sleep()导致管道破裂?

时间:2020-03-12 01:36:37

标签: c linux posix

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

编写一个程序,该程序创建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秒钟,只是填满了我想的管道。 我无法理解此问题,一段时间以来一直在寻找答案。

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

1 个答案:

答案 0 :(得分:1)

问题出在你的循环中。

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

将迭代11次。

尝试something.round < 10

也可以在子对象中刷新标准输出,或调用exit而不是_exit

相关问题