父进程没有完全从命名管道读取数据

parent process not reading the data from named pipe completely

本文关键字:管道 读取 数据 从命 进程      更新时间:2023-10-16

我正在尝试分叉一个进程并执行一个命令。我正在创建一个命名管道,并尝试从将STDOUT写入管道的子进程执行命令。父进程将从管道中读取。我的问题是父进程没有完全从管道中读取数据。这是代码。

fifo_fd = mkfifo(MY_FIFO, 0666);
FILE *fp = fdopen(fifo_fd, "r");
childpid = fork();
if (childpid == 0)
{
   dup2(fifo_fd, STDOUT_FILENO);
   dup2(fifo_fd, STDERR_FILENO);
   close(fifo_fd);
   execv(arg_list[0], arg_list);
   _exit (127);
}
else
{
   //parent process
   if(waitpid(childpid, &status,WNOHANG ) == -1) {
     // now we kill the child and return failure.
   }
   fcntl(fd, F_SETFL, O_NONBLOCK);
   while((fgets(buf, sizeof(buf)-1,fp))) {
   strcat(result,buf); //we copy the buf to result
}
return success;
}

您希望使用管道,而不是fifo,这样就不需要创建文件系统条目。正如@Christian所说,您还需要确保两个进程同时运行,否则pipe/fifo可能会阻塞并导致程序挂起。

试试下面这样的方法。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
    int pipe_fd[2];
    pipe(pipe_fd);
    if (fork() == 0) {
        dup2(pipe_fd[1], STDOUT_FILENO);
        dup2(pipe_fd[1], STDERR_FILENO);
        close(pipe_fd[0]);
        close(pipe_fd[1]);
        char *arg_list[] = {"/bin/echo", "hello", 0};
        execv(arg_list[0], arg_list);
        __builtin_unreachable();
    } else {
        close(pipe_fd[1]);
        char buf[32];
        int count;
        for (;;) {
            count = read(pipe_fd[0], buf, sizeof(buf));
            if (count <= 0) break;
            write(STDOUT_FILENO, buf, count);
        }
    }
    return 0;
}