我几乎看不懂管道的手册页,所以我需要帮助理解如何在外部可执行文件中获取管道输入。
我有 2 个程序: main.o & log.o
我写了 main.o fork 。这是它在做什么:
我需要用于将主管道连接到 的 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> ");
}
最佳答案
我想这就是你要做的:
1.主叉,父通过管道将消息传递给子。
2. child 从管道接收消息,将消息重定向到 STDIN,执行日志。
3.记录从STDIN接收消息,做一些事情。
做到这一点的关键是dup2重定向文件描述符,从管道到标准输入。
这是修改后的简单版本:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
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;
}
关于C 管道到另一个程序的 STDIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20187734/