我幾乎不能理解pipe的手冊頁,所以我需要幫助理解如何在外部可執行文件中使用管道輸入。C Pipe到另一個程序的STDIN
我有2種方案:main.o & log.o
我寫main.o到餐桌。下面是它在做什麼:
- 家長叉將管數據給孩子
- 兒童叉將EXEClog.o
我需要的兒童叉主要管到STDIN的log.o
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> ");
}