父进程没有完全从命名管道读取数据
parent process not reading the data from named pipe completely
我正在尝试分叉一个进程并执行一个命令。我正在创建一个命名管道,并尝试从将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;
}
相关文章:
- 先进先出:一个进程永远不会从管道读取
- read() 在 select() 阻塞之后,当从生成的进程从管道读取时
- 读取文件挂在管道读取上
- 使用两个不同的管道C 读取和写入相同的过程
- 启动子进程时的争用条件导致从管道读取挂起
- 为什么从管道读取时libc++getline会阻塞,而libstdc++getline不会
- 如何从 GStreamer 管道读取数据中的特定字段
- 命名管道读取超时
- 使用“反引号”而不是管道读取值 |C++
- 从管道读取输入时出现scanf问题
- 从 Linux 中的多个非阻塞命名管道读取
- 父进程没有完全从命名管道读取数据
- 获取错误代码 998 尝试从命名管道读取时对内存位置的访问无效
- 无法从匿名管道读取
- 在dup2()之后使用std::cin从管道读取
- 为什么 ReadFile() 不返回 0 ?程序尝试永远从管道读取数据
- 执行控制台程序,写入标准输入并使用管道读取结果
- 从管道读取随机失败
- 为什么我的程序在管道读取过程中冻结?
- 为什么可以'd '从管道读取比我自己的程序使用ifstream更快