简体   繁体   English

从管道读取时进程挂起-Linux

[英]Process suspended when reading from pipe - linux

I've written the following code: 我编写了以下代码:

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

#define BUFF 200


int main(int argc, char *argv[]) {

    char write_buffer[BUFF];
    char read_buffer[BUFF];

    strcpy(write_buffer, "This string supposed to be sent from parent to child");

    int fds[2];
    pid_t pid;

    if ((pid=fork())==-1) {
        perror("fork error");
    }

    if (pipe(fds)==-1) {
        perror("pipe error");
    }


    else if (pid==0) { // child


        int bytes;
        if ((bytes=read(fds[0], read_buffer, BUFF))==-1) {
            perror("read error");
        }
        else {
            printf("read %d bytes from pipe\n", bytes);
        }
    }

    else { // parent

        if (write(fds[1], write_buffer, strlen(write_buffer))==-1) {
            perror("write error");
        }

        printf("FLAG to check if write() went through\n"); // this will print!

        wait(NULL);
    }
}

The simple code above is an attempt to send data through a pipe, from a parent process to a child process. 上面的简单代码是尝试通过管道将数据从父进程发送到子进程的尝试。
Problem is, the execution is suspended for some reason... 问题是执行由于某种原因而被暂停...
The child process blocked at the read() system call (or at least it seems to be), and the parent just sits there, waiting for it to finish, but that never happens. 子进程在read()系统调用(或至少看起来好像是)上受阻,而父进程只是坐在那里,等待它完成,但这从未发生。
What is the problem here? 这里有什么问题? clearly, the parent process has enough time to write write_buffer to the pipe, so the child process won't call read() on an empty pipe. 显然,父进程有足够的时间将write_buffer写入管道,因此子进程不会在空管道上调用read()。

You fork and then you create the pipe so each process is going to its own set of pipes that don't talk to each other. 您先进行fork ,然后创建管道,以便每个进程都将使用各自的不互相通信的管道。

Just switch the code around and call pipe before fork and you should be good to go. 只需切换代码并在fork之前调用pipe ,您应该一切顺利。

Also, though it probably won't matter here, get in the habit of reading and writing in a loop. 另外,尽管这里可能无关紧要,但要养成循环阅读和写作的习惯。 read & write are not guaranteed to get nor put all the data you request in one call. readwrite并不能保证一次调用即可获取或放入您请求的所有数据。 Likewise, close your pipes after you done. 同样,完成后关闭管道。 Closing the write end of the pipe will signal to the reader that the end-of-file has been reached. 关闭管道的写端将向读取器发送信号,表明已到达文件末尾。

while (read(fds[0], read_buffer, sizeof(read_buffer)) > 0) 
{
    //process bytes read
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM