gpt4 book ai didi

c - 使用管道复制字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:42:52 26 4
gpt4 key购买 nike

我编写了以下代码,使用 fork 和管道将字符串“hello world”复制到另一个字符数组,而不是使用标准库函数或标准 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;

}

最佳答案

您的 printf 正在写入 stdout - 但在父级和子级中,您已将文件描述符 1 重定向到管道,所以这就是 >printf 将输出。

使用 fprintf(stderr, ...) 而不是 printf(...) - 然后您将能够看到输出,因为 stderr 仍然指向您的终端。

请注意,您有几个错误:

  • 子进程完成后应该调用_exit(0),否则会掉入父进程;
  • write 应该使用strlen(string) + 1,以便写入 nul 终止符。

关于c - 使用管道复制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2092687/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com