Unix 进程在写入管道之前读取数据

Unix 进程在写入管道之前读取数据,unix,fork,ipc,pipe,Unix,Fork,Ipc,Pipe,我正在尝试创建管道并将其与fork()一起使用。但我对执行的顺序感到困惑。 进程在将任何内容写入管道之前从管道读取数据。有时它运行正常。但有时,在写之前先读,但仍能给出正确的输出 #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(void) { int fd[2], nbytes,ret; pid_t childpid; char

我正在尝试创建管道并将其与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;
}
#包括
#包括
#包括
内部主(空)
{
int-fd[2],n字节,ret;
pid_t childpid;
字符字符串[]=“你好,世界!\n”;
字符读取缓冲区[80];
管道(fd);
如果(!fork())
{
关闭(fd[0]);
printf(“书写…”);
写入(fd[1],string,(strlen(string)+1));
出口(0);
}
否则{
关闭(fd[1]);
printf(“阅读…”);
nbytes=读取(fd[0],读取缓冲区,sizeof(读取缓冲区));
printf(“收到的字符串:%s”,readbuffer);
等待(空);
}
返回0;
}

之所以发生这种情况,是因为调度器在子进程之前调度父进程,因此
它导致在写入之前执行读取操作。另一方面,输出可以是
正如预期的那样,有时调度程序会首先调度子进程

解决方案: 1.您需要使用信号灯等同步技术来同步数据
父母和孩子。 2.或者,您可以让父进程等待子进程完成。考虑< BR> 以下代码:

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)”语句,并将等待子项完成
然后继续执行