将控制台输入重定向到 c 中的管道
Redirect console input to pipe in c
我想要一个类似的功能:
cat >&5
其中 5 是管道 fd
但在 c.
有没有一种优雅的方法来实现它,还是我必须将标准输入读取到缓冲区并将其写入管道(或者只执行上面的命令)?
int fd[2];
pipe(fd);
...
... (fork)
... kid is reading from fd[0]
//Parent:
//method 1
char line[255];
int got;
while((got=read(0, line, 255))>0){
write(fd[1], line, got);
}
//method 2
char cmd[25];
snprintf(cmd, 25, "cat >&%d", fd[1]);
system(cmd);
两种方法都有效,我只是想知道是否有更好的方法来完成任务...
下面是我设法做到的方法的总结:
//Parent:
//method 1
char line[255];
int got;
while((got=read(0, line, 255))>0){
write(fd[1], line, got);
}
//method 2
char cmd[25];
snprintf(cmd, 25, "cat >&%d", fd[1]);
system(cmd);
//method 3
while (1) splice(0, NULL, fd[1], NULL, 255, 0);
所有方法都可能在另一个线程中让父级继续。
我也添加了 splice,这似乎确实符合我们的要求。
我想要一个类似的功能:
cat >&5
其中 5 是管道 fd
但在 c.
有没有一种优雅的方法来实现它,还是我必须将标准输入读取到缓冲区并将其写入管道(或者只执行上面的命令)?
int fd[2];
pipe(fd);
...
... (fork)
... kid is reading from fd[0]
//Parent:
//method 1
char line[255];
int got;
while((got=read(0, line, 255))>0){
write(fd[1], line, got);
}
//method 2
char cmd[25];
snprintf(cmd, 25, "cat >&%d", fd[1]);
system(cmd);
两种方法都有效,我只是想知道是否有更好的方法来完成任务...
下面是我设法做到的方法的总结:
//Parent:
//method 1
char line[255];
int got;
while((got=read(0, line, 255))>0){
write(fd[1], line, got);
}
//method 2
char cmd[25];
snprintf(cmd, 25, "cat >&%d", fd[1]);
system(cmd);
//method 3
while (1) splice(0, NULL, fd[1], NULL, 255, 0);
所有方法都可能在另一个线程中让父级继续。
我也添加了 splice,这似乎确实符合我们的要求。