在c中将控制台输入重定向到管道

时间:2017-03-30 14:21:48

标签: c pipe stdin

我想要一个类似的功能:

cat >&5 其中5是管道fd

但是在c。

是否有一种优雅的方法来实现,或者我必须将stdin读取到缓冲区并将其写入管道(或者只是执行上述命令)?

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);

这两种方法都有效,我只是想知道是否有更好的方法来完成任务......

1 个答案:

答案 0 :(得分: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);

//method 3
while (1) splice(0, NULL, fd[1], NULL, 255, 0);

所有方法都可能在另一个线程中让父母继续。

我已经添加了拼接,这似乎确实完全符合我们的要求。

相关问题