使用管道的字符串复制

时间:2010-01-19 10:16:02

标签: c linux pipe fork dup

我编写了以下代码,使用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;

   }

3 个答案:

答案 0 :(得分:4)

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

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

请注意,您有几个错误:

  • 孩子应该在完成后调用_exit(0),否则会掉入父代码中;
  • write应使用strlen(string) + 1,以便它写入nul终结符。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我猜这些管道正在阻塞IO,因此除非管道被其他进程关闭,否则读取将不会返回。那,和printf做缓冲IO,阻止你得到任何输出。