【发布时间】:2015-04-23 13:07:09
【问题描述】:
你好 stackoverflow 我试图创建一个程序来执行一个子 shell 进程并将他的 I/O 重定向到一个管道,以便与他的父进程通信。
我可以通过写入管道 (wpipefd) 执行命令,但我无法从读取管道 (rpipefd) 上的 shell 进程中获得响应。
根据 Strace 到目前为止我有 3 个错误:首先,读取函数阻塞了程序,所以我将读取管道的读取 fd 设为非阻塞(rpipe[0])。然后我的 read 函数出现 EAGAIN 错误...最后,当我在使用 dup2() 之后在分叉进程中关闭来自 rpipe (close(rpipefd[0])) 的 read fd 时,出现 EPIPE 错误。
我不明白我做错了什么。这是我到目前为止所做的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#define BUF_SIZE 1024
int main(int argc, char **argv)
{
int rpipefd[2], wpipefd[2], pid;
pipe(rpipefd);
pipe(wpipefd);
char buffer[BUF_SIZE] = {0};
int flags = fcntl(rpipefd[0], F_GETFL, 0);
fcntl(rpipefd[0], F_SETFL, flags | O_NONBLOCK);
pid = fork();
if(pid == 0)
{
close(rpipefd[0]);
dup2(rpipefd[1],1);
dup2(rpipefd[1],2);
close(wpipefd[1]);
dup2(wpipefd[0],0);
close(rpipefd[1]);
close(wpipefd[0]);
execl("/bin/sh","/bin/sh",NULL);
}
close(wpipefd[0]);
write(wpipefd[1],"echo helloWorld",strlen("echo helloWorld"));
close(rpipefd[1]);
read(rpipefd[0],buffer,BUF_SIZE);
//perror("read()");
printf("%s",buffer);
exit(0);
}
请帮忙!
【问题讨论】:
标签: c linux shell redirect pipe