【发布时间】:2013-11-25 08:25:56
【问题描述】:
我几乎无法理解管道的手册页,所以我需要帮助了解如何在外部可执行文件中获取管道输入。
我有 2 个程序:main.o & log.o
我写了 main.o 来分叉。这是它正在做的事情:
- 父分叉将管道数据给子
- 子分叉将执行 log.o
我需要子叉子用于主管道到 log.o
的 STDINlog.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> ");
}
【问题讨论】: