[英]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所說,您還需要確保兩個進程同時運行,否則管道/ 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.