在 Linux 中使用管道标准输入和输出执行子进程
考虑以下函数:
string f(string s) { string r = system("foo < s"); return r; }
这个函数尝试使用字符串 s 作为其标准输入来执行“foo”程序,捕获程序的标准输出字符串 r。然而,这种方法并不可行。
要正确实现此功能,需要结合 Linux 系统调用或 POSIX 函数:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int createChild(const char *szCommand, char *const aArguments[], char *const aEnvironment[], const char *szMessage) { int aStdinPipe[2]; int aStdoutPipe[2]; int nChild; char nChar; 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); } // run child process image // (replace this with any `exec*` function you find easier to use) execve(szCommand, aArguments, aEnvironment); // if we get here at all, an error occurred, but we are in the child // process, so just exit exit(errno); } else if (nChild > 0) { // parent continues here // close unused file descriptors close(aStdinPipe[PIPE_READ]); close(aStdoutPipe[PIPE_WRITE]); // send message to child (if provided) if (NULL != szMessage) { write(aStdinPipe[PIPE_WRITE], szMessage, strlen(szMessage)); } // read child's output while (read(aStdoutPipe[PIPE_READ], &nChar, 1) == 1) { write(STDOUT_FILENO, &nChar, 1); } // close pipes 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; }
此函数 createChild 在父进程和子进程,将子进程的标准输入和输出重定向到管道。然后,父进程可以通过管道将输入发送给子进程,并从同一管道读取子进程的输出。
以上是如何正确地将标准输入和输出传送到 Linux 中的子进程?的详细内容。更多信息请关注PHP中文网其他相关文章!