【问题标题】:Process reads data before writing into pipe进程在写入管道之前读取数据
【发布时间】:2014-08-24 07:37:34
【问题描述】:

我正在尝试创建管道并将其与 fork() 一起使用。但我对执行顺序感到困惑。 在将任何内容写入管道之前,进程会从管道中读取数据。有时它运行正确。但有时,先读再写,但仍然给出正确的输出。

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
    int     fd[2], nbytes,ret;
    pid_t   childpid;
    char    string[] = "Hello, world!\n";
    char    readbuffer[80];

    pipe(fd);
    if(!fork())
    {
            close(fd[0]);
            printf("Writing...");
            write(fd[1], string, (strlen(string)+1));
            exit(0);
    }
    else{
            close(fd[1]);
            printf("Reading...");
            nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
            printf("Received string: %s", readbuffer);
            wait(NULL);

    }
return 0;
}

【问题讨论】:

    标签: unix fork ipc pipe


    【解决方案1】:

    这是因为调度程序在子进程之前调度父进程,因此
    它导致在写入之前进行读取操作。另一方面,输出可能是
    正如预期的那样,有时调度程序会首先安排孩子。

    解决方案: 1.您需要使用信号量等同步技术来同步
    父母和孩子。 2.或者你可以让父进程等到子进程完成。考虑
    以下代码:

    int child_status;  // declare this variable
    
    /* add the following line to the else clause */
    else
    {
        close(fd[1]);
        wait(&child_status);
        // rest of your code
    }
    

    说明: 如果父进程在子进程之前调度,那么它的执行将在
    它会找到“wait(&child_status)”语句并等待孩子完成
    它的执行,然后继续进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      相关资源
      最近更新 更多