我已经写下代码复制一串"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;

   }
有帮助吗?

解决方案

你的 printf都是写到 stdout -但在父母和孩子,你已经重新定向的文件描述的1个管,所以这就是我的 printf 出去。

而不是的 printf(...), 使用 fprintf(stderr, ...) -然后你就可以看出,由于 stderr 还是指向你的终端。

注意,你有一对夫妇的错误:

  • 儿童应该叫 _exit(0) 当这样做,否则会下降到父母代码;
  • write 应该使用 strlen(string) + 1, ,因此,它写nul的终结者。

其他提示

尝试添加 “\ n” 个,像printf("\nParent buf: %s\n", buf);

我猜这些管道正在做阻塞IO,所以读根本不会返回,除非管由其他进程关闭。也就是说,和printf做着从得到的任何输出缓冲IO,防止你。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top