怎樣 redirect 一個將被 exec 執行的 process的standard input and output?

thomas269 2003-01-30 12:16:02
現在我有一個普通的program, for example:
#include <stdio.h>
main()
{
int i;
scanf("%d", &i);
printf("%d\n", i * 2);
return 0;
}
之後, 我想用另一個program, 把它的standard i/o都handle住, 然後模擬它的input and 取得它的 output, 我試過好多方法, 不是只handle到它的input, 就是只handle到它的output. 不能input and output同時handle到.
有邊位懂得呀!! 萬分感激!
...全文
70 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
thomas269 2003-01-30
  • 打赏
  • 举报
回复
問題已經解決la, 上面的代碼是行得通的, 只是因為 printf把data bufferred, 所以要用fflush來force佢output.
配合setlinebuf()就可以不用fflush都可以了

但有一個問題, 就是上面那個simple program就變成了
#include <stdio.h>
main()
{
int i;
setlinebuf(stdout);
scanf("%d", &i);
printf("%d\n", i * 2);
return 0;
}
這是由於pipe default的bufferred mode不是line buffer, 怎樣可以改變它的descriptor成為line buffer,而不用在被exec的program中加入setlinebuf(stdout)
thx
thomas269 2003-01-30
  • 打赏
  • 举报
回复
如pipe,我用過以下代碼:
void redirectio_exec(char * const filename, int fd[])
{
char * const argv[] = {filename, NULL};
int fd1[2], fd2[2];

pipe(fd1);
pipe(fd2);

if (fork() == 0)
{
close(fd1[0]);
dup2(fd1[1], STDOUT_FILENO);

dup2(fd2[0], STDIN_FILENO);
close(fd2[1]);

close(fd1[1]);
close(fd2[0]);

execvp(filename, argv);
exit(0);
}

close(fd1[1]);

close(fd2[0]);

fd[0] = fd1[0];
fd[1] = fd2[1];
}
thomas269 2003-01-30
  • 打赏
  • 举报
回复
試過la, pipe and fifo都試過, 連 PF_UNIX socket都試過la, 但係都不行, 都是just input or output is allowable
lixingyi 2003-01-30
  • 打赏
  • 举报
回复
新建process来执行另一个program,用pipe重定向输入和输出

23,114

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧