代码之家  ›  专栏  ›  技术社区  ›  manav m-n

使用管道复制字符串

  •  1
  • manav m-n  · 技术社区  · 15 年前

    我编写了以下代码,使用fork和pipes将字符串“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;
    
       }
    
    3 回复  |  直到 15 年前
        1
  •  4
  •   caf    15 年前

    你的 printf S正在写信给 stdout -但是在父级和子级中,您已经将文件描述符1重定向到管道,因此 普林特 输出就会消失。

    而不是 printf(...) 使用 fprintf(stderr, ...) -然后你就可以看到输出了,因为 stderr 仍指向您的终端。

    请注意,您有几个错误:

    • 孩子应该打电话 _exit(0) 完成后,否则将进入父代码;
    • 这个 write 应该使用 strlen(string) + 1 这样它就写了nul终止符。
        2
  •  0
  •   user59634    15 年前

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

        3
  •  0
  •   Erich Kitzmueller    15 年前

    我猜那些管道正在阻塞IO,所以read不会返回,除非管道被另一个进程关闭。这样,以及printf执行缓冲IO,会阻止您获得任何输出。