c - 从管道读取时进程暂停 - linux

标签 c linux posix pipe

我写了下面的代码:

#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);
    }
}

上面的简单代码是尝试通过管道从父进程向子进程发送数据。
问题是,由于某种原因,执行被暂停了……
子进程在 read() 系统调用处被阻塞(或者至少看起来是这样),而父进程只是坐在那里,等待它完成,但这种情况从未发生过。
这里有什么问题?显然,父进程有足够的时间将 write_buffer 写入管道,因此子进程不会在空管道上调用 read()。

最佳答案

fork 然后创建管道,这样每个进程都将转到自己的一组管道,这些管道不会相互通信。

只需切换代码并在 fork 之前调用 pipe 就可以了。

此外,尽管在这里可能无关紧要,但请养成循环读写的习惯。 readwrite 不能保证在一次调用中获取或放入您请求的所有数据。同样,完成后关闭管道。关闭管道的写入端将向读取器发出信号,表明已到达文件末尾。

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

关于c - 从管道读取时进程暂停 - linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23429449/

相关文章:

比较列(字符类型)在使用 proc 的 where 子句中使用主机变量

C++ 在 LD_LIBRARY_PATH 上查找文件

c - 在 spawn() 之后使用 _exit() 或 exit()?

c++ - typedef 函数指针?

linux - 中断处理(Linux/通用)

Perl 将本地时间格式的时间转换为 YYYYMMDD

c - 与 O_CREAT|O_EXCL 相反

linux - 如何从服务器 SCP 选定的文件

linux - python 3 没有名为 _tkinter 的模块

c++ - fstat() 在预加载的 mmap() 系统调用中无法按预期工作