我想要做一个简单的fork操作 -> 执行另一个程序 -> 对子进程说“hello” -> 读取返回值 -> 打印接收到的内容。作为子进程使用的程序只是等待任何输入行并将类似“hello there!”的内容打印到stdout。
这是我的“主机”程序(无法工作):
这是我的“主机”程序(无法工作):
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#define IN 0
#define OUT 1
#define CHILD 0
main ()
{
pid_t pid;
int pipefd[2];
FILE* output;
char buf[256];
pipe(pipefd);
pid = fork();
if (pid == CHILD)
{
printf("child\n");
dup2(pipefd[IN], IN);
dup2(pipefd[OUT], OUT);
execl("./test", "test", (char*) NULL);
}
else
{
sleep(1);
printf("parent\n");
write(pipefd[IN], "hello!", 10); // write message to the process
read(pipefd[OUT], buf, sizeof(buf));
printf("received: %s\n", buf);
}
}
I get this:
child
[.. waits 1 second ..]
parent
received:
我漏掉了什么?谢谢!
编辑 (test.c):
按要求,这是子程序:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getln(char line[])
{
int nch = 0;
int c;
while((c = getchar()) != EOF)
{
if(c == '\n') break;
line[nch] = c;
nch++;
}
if(c == EOF && nch == 0) return EOF;
return nch;
}
main()
{
char line[20];
getln(line);
printf("hello there!", line);
fflush(stdout);
return 0;
}
pipe
的说明,"未指定 fildes[0] 是否也打开了写入权限,以及 fildes[1] 是否也打开了读取权限。" - Jasonsocketpair
或者伪终端。 - zwol