linux更换子进程的标准输入,的Linux 3.0:与管道标准输入执行子进程/标准输出

由eerpini提供的代码不能按照书面形式工作。请注意,例如,之后使用在父项中关闭的管道末端。看看

close(wpipefd[1]);

和随后写入该封闭描述符。这只是换位,但它显示此代码从未被使用过。以下是我测试过的一个版本。不幸的是,我改变了代码风格,所以这不被接受为eerpini代码的编辑。

唯一的结构性变化是我只重定向子项中的I/O(注意dup2调用只在子路径中)。这非常重要,否则父项I/O会混乱。感谢eerpini提供的初始答案,我在开发这个答案时使用了这个答案。

#define PIPE_READ 0

#define PIPE_WRITE 1

int createChild(const char* szCommand, char* const aArguments[], char* const aEnvironment[], const char* szMessage) {

int aStdinPipe[2];

int aStdoutPipe[2];

int nChild;

char nChar;

int nResult;

if (pipe(aStdinPipe) < 0) {

perror("allocating pipe for child input redirect");

return -1;

}

if (pipe(aStdoutPipe) < 0) {

close(aStdinPipe[PIPE_READ]);

close(aStdinPipe[PIPE_WRITE]);

perror("allocating pipe for child output redirect");

return -1;

}

nChild = fork();

if (0 == nChild) {

// child continues here

// redirect stdin

if (dup2(aStdinPipe[PIPE_READ], STDIN_FILENO) == -1) {

exit(errno);

}

// redirect stdout

if (dup2(aStdoutPipe[PIPE_WRITE], STDOUT_FILENO) == -1) {

exit(errno);

}

// redirect stderr

if (dup2(aStdoutPipe[PIPE_WRITE], STDERR_FILENO) == -1) {

exit(errno);

}

// all these are for use by parent only

close(aStdinPipe[PIPE_READ]);

close(aStdinPipe[PIPE_WRITE]);

close(aStdoutPipe[PIPE_READ]);

close(aStdoutPipe[PIPE_WRITE]);

// run child process image

// replace this with any exec* function find easier to use ("man exec")

nResult = execve(szCommand, aArguments, aEnvironment);

// if we get here at all, an error occurred, but we are in the child

// process, so just exit

exit(nResult);

} else if (nChild > 0) {

// parent continues here

// close unused file descriptors, these are for child only

close(aStdinPipe[PIPE_READ]);

close(aStdoutPipe[PIPE_WRITE]);

// Include error check here

if (NULL != szMessage) {

write(aStdinPipe[PIPE_WRITE], szMessage, strlen(szMessage));

}

// Just a char by char read here, you can change it accordingly

while (read(aStdoutPipe[PIPE_READ], &nChar, 1) == 1) {

write(STDOUT_FILENO, &nChar, 1);

}

// done with these in this example program, you would normally keep these

// open of course as long as you want to talk to the child

close(aStdinPipe[PIPE_WRITE]);

close(aStdoutPipe[PIPE_READ]);

} else {

// failed to create child

close(aStdinPipe[PIPE_READ]);

close(aStdinPipe[PIPE_WRITE]);

close(aStdoutPipe[PIPE_READ]);

close(aStdoutPipe[PIPE_WRITE]);

}

return nChild;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值