我编写了以下代码,使用 fork 和管道将字符串“hello world”复制到另一个 char 数组,而不是使用标准库函数或标准 i/o 流。该程序编译成功,但我没有得到任何输出。甚至,没有显示 printf 的输出。
# include <string.h>
# include <unistd.h>
# include <stdio.h>
char string[] = "hello world";
int main()
{
int count, i;
int toPar[2], toChild[2];
char buf[256];
pipe(toPar);
pipe(toChild);
if (fork() == 0)
{
printf("\n--- child process ---");
close(0);
dup(toChild[0]);
close(1);
dup(toPar[1]);
close(toPar[1]);
close(toChild[0]);
close(toPar[0]);
close(toChild[1]);
for (;;)
{
if ((count = read(0, buf, sizeof(buf))) == 0)
break;
printf("\nChild buf: %s", buf);
write(1, buf, count);
}
}
printf("\n--- parent process ---");
close(1);
dup(toChild[1]);
close(0);
dup(toPar[0]);
close(toPar[1]);
close(toChild[0]);
close(toPar[0]);
close(toChild[1]);
for (i = 0; i < 15; i++)
{
write(1, string, strlen(string));
printf("\nParent buf: %s", buf);
read(0, buf, sizeof(buf));
}
return 0;
}