1

我正在尝试熟悉管道,并且我编写了一个非常愚蠢的鹦鹉程序,它基本上接收来自键盘的输入,然后显示完全相同的内容:

if (pipe(fd) < 0) {
        perror("Pipe");
        exit(1);
    }

    if ( ( pid = fork() < 0 ) ) {
        perror("Fork");
        exit(1);
    }

    if ( pid > 0 ) //If I'm the parent...
    {
        printf("Parent!");
        close(fd[0]);
        //as long as something is typed in and that something isn't 
        // the word "stop"
        while (((n = read(STDIN_FILENO, buffer, BUFFERSIZE)) > 0) && 
               (strncmp(buffer, "stop", 4) != 0))
        {
            //shove all the buffer content into the pipe
            write(fd[1], buffer, BUFFERSIZE);
        }
    }
    else //If I am the child...
    {
        printf("Child!");
        close(fd[1]);

        //as long as there's something to read
        while (pipe_read = read(fd[0], buf, sizeof(buf)) > 0)
        {
            //display on the screen!
            write(STDOUT_FILENO, buf, pipe_read);
        }
    }

我明白为什么这个程序没有参与循环,那是因为父级从不执行,结果我得到Child! Child!了输出,我不知道为什么。

4

1 回答 1

7

改变

if ( ( pid = fork() < 0 ) ) 

if ( (pid = fork()) < 0 )

没有正确的括号pid被设置(fork() < 0)0.

于 2013-06-06T16:34:11.590 回答