分叉后父母永远不会执行

时间:2013-06-06 16:26:38

标签: c fork

我正在尝试熟悉管道,我写了一个非常愚蠢的鹦鹉程序,基本上从键盘输入,然后显示完全相同的事情:

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!作为输出,我无法弄清楚原因。

1 个答案:

答案 0 :(得分:7)

更改

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

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

如果没有正确的括号pid被设置为(fork() < 0),那就是0