C

时间:2016-03-31 18:08:58

标签: c operating-system

请考虑以下代码:

#include<stdio.h>
#include <unistd.h>
#include <sys/wait.h>

#define READ 0
#define WRITE 1

int fd[2];

void execute(char*[], int mode);

int main()
{
char * command1[3] = {"cat", "output.txt", NULL};
char * command2[3] = {"wc", "-l", NULL};

pipe(fd);                       // creating pipe...


execute(command1, WRITE);               // execute command1 and write output to pipe
execute(command2, READ);                // execute command2 and get output from pipe


return 0;
}

//....................... DEFINATION .......................

void execute(char* command[], int mode)
{
pid_t pid;

pid = vfork();
if(pid == 0)
{
    if(mode == WRITE)               // writes successfully to the pipe...
    {
        close(1);
        dup(fd[WRITE]);
        close(fd[READ]);
        close(fd[WRITE]);

        execvp(command[0], command);
    }

    else if(mode == READ)               // doesnot read from the pipe and goes to the wait state...
    {
        close(0);
        dup(fd[READ]);
        close(fd[WRITE]);
        close(fd[READ]);

        execvp(command[0], command);
    }
}

else if(pid > 0)
{
    wait(NULL);
}

}

我正在尝试编写一个程序,该程序使用带有stdout的管道从第一个进程被重定向为第二个进程的stdin。但我遇到了一个问题。上面的代码执行第一个命令&#34; command1&#34;并成功地将数据写入管道。但是第二个命令&#34; command2&#34;不会从管道中读取数据并进入某种等待/阻塞状态。我不知道问题是什么。如果成功完成对管道的写入,那么为什么从管道读取不成功?

帮助将受到高度关注。在此先感谢!!!

1 个答案:

答案 0 :(得分:2)

因为父母没有关闭管道的WRITE部分,所以读者被阻止等待永远不会来的数据(父母正在等待他被阻止的孩子)。

只需在致电close(fd[WRITE]);功能之间添加对execute的通话。

总是关闭管道的未使用端......

您也可能不会以这种方式调用wait(您的子进程逐个执行),在调用wait后调用execute(调用等待两次)。

相关问题