gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:53:26 26 4
gpt4 key购买 nike

我正在尝试 fork 一个进程并执行一个命令。我正在创建一个命名管道并尝试从将 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 所说,您还需要确保两个进程同时运行,否则管道/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;
}

关于c++ - 父进程没有完全从命名管道读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12348584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com