C管道到另一个程序的STDIN
我几乎无法理解管道的手册页,所以我需要帮助理解如何在外部可执行文件中获取管道输入。
我有2个程序: main.o和log.o
我把main.o写成了fork。 这是它正在做的事情:
- 父fork会将数据传递给子级
- 子fork将执行 log.o
我需要子fork for main来管道到log.o的 STDIN
log.o只是将带有时间戳的STDIN和日志带到文件中。
我的代码是由我不记得的各种StackOverflow页面的一些代码和管道的手册页组成的:
printf("\n> "); while(fgets(input, MAXINPUTLINE, stdin)){ char buf; int fd[2], num, status; if(pipe(fd)){ perror("Pipe broke, dood"); return 111; } switch(fork()){ case -1: perror("Fork is sad fais"); return 111; case 0: // Child close(fd[1]); // Close unused write end while (read(fd[0], &buf, 1) > 0) write(STDOUT_FILENO, &buf, 1); write(STDOUT_FILENO, "\n", 1); close(fd[0]); execlp("./log", "log", "log.txt", 0); // This is where I am confused _exit(EXIT_FAILURE); default: // Parent data=stuff_happens_here(); close(fd[0]); // Close unused read end write(fd[1], data, strlen(data)); close(fd[1]); // Reader will see EOF wait(NULL); // Wait for child } printf("\n> "); }
我想这就是你要做的事情:
1.主叉,父通过管道向子传递消息。
2.子接收来自管道的消息,将消息重定向到STDIN,执行日志。
3.记录来自STDIN的消息,做点什么。
执行此操作的关键是dup2重定向文件描述符,从管道到STDIN。
这是修改后的简单版本:
#include #include #include #include #include int main(int argc, char *argv[]) { int fd[2]; char buf[] = "HELLO WORLD!"; if(pipe(fd)){ perror("pipe"); return -1; } switch(fork()){ case -1: perror("fork"); return -1; case 0: // child close(fd[1]); dup2(fd[0], STDIN_FILENO); close(fd[0]); execl("./log", NULL); default: // parent close(fd[0]); write(fd[1], buf, sizeof(buf)); close(fd[1]); wait(NULL); } printf("END~\n"); return 0; }
我可以建议一个更简单的方法。 有一个叫做popen()
的函数。 它的工作方式与system()
函数非常相似,除了您可以读取或写入子stdin/stdout
。
例:
int main(int argc, char* argv[]) { FILE* fChild = popen("logApp.exe", "wb"); // the logger app is another application if (NULL == fChild) return -1; fprintf(fChild, "Hello world!\n"); pclose(fChild); }
在控制台中写下“ man popen ”以获得完整描述。
你可以使用dup2
请参阅在C中将UNIX管道描述符映射到stdin和stdout