【发布时间】:2011-12-17 14:56:51
【问题描述】:
我正在尝试做一个简单的 fork -> 执行另一个程序 -> 对那个子进程说“你好” -> 读回一些东西 -> 打印收到的内容。
作为子程序使用的程序只是等待任何输入行并在标准输出中打印一些内容,例如“你好!”
这是我的“主机”程序(不起作用):
#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);
}
}
我明白了:
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;
}
【问题讨论】: