Re: [問題] 關於標準輸出與標準輸入
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
using namespace std;
int main(int argc, const char *argv[])
{
int fd[2];
if(pipe(fd) < 0)
{
printf("pipe error\n");
exit(-1);
}
pid_t child_pid = fork();
if (child_pid == -1)
{
printf("fork error\n");
exit(-1);
}
if (child_pid == 0) // child
{
close(fd[0]);
dup2 (fd[1], fileno (stdout));
close(fd[1]);
write(fileno(stdout), "hello", 5);
}
else // parent
{
close(fd[1]);
dup2 (fd[0], fileno (stdin));
close(fd[0]);
char buf[256];
ssize_t len = fread(buf, 1, 256, stdin);
buf[len] = 0;
printf("%d # buf: %s\n", len, buf);
}
return 0;
}
這個還是需要用到 pipe(), 因為沒印象, apue 也不在手中,
我不確定 apue 是不是有介紹 pipe() 的實作,
只能給你這樣的參考資料。
child process write hello to stdout,
parent process read from stdin.
※ 引述《wind00962 (Light)》之銘言:
: 最近研究所教授要我做一個
: 如何要在linux gcc下
: 程式fork後
: 父process用標準輸入去讀子process的輸出內容
: 不能用管道或ipc機制
: 想了半天,不知道該用哪個函式
: 謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 58.114.141.207
推
11/04 23:57, , 1F
11/04 23:57, 1F
→
11/04 23:57, , 2F
11/04 23:57, 2F
→
11/04 23:57, , 3F
11/04 23:57, 3F
剛剛試了另外一招, 使用 pseudo terminal,
man openpty
基本上把 pipe 換成 openpty 就可以了。
我在想原 po 老師的意思是不是不能用 popen/pclose
※ 編輯: descent 來自: 58.114.141.207 (11/05 00:21)
推
11/05 01:00, , 4F
11/05 01:00, 4F