更多(1)写入stdout而不实际应用寻呼机

时间:2013-11-23 15:24:49

标签: c exec system-calls pager

我正在尝试创建一个运行printenv的C程序grep [参数] |排序|更多,到目前为止一切正常,程序正在按照预期将已排序的环境变量打印到stdout。唯一的问题是没有寻呼机,即使我正在启动的最后一个进程 - 唯一一个带有stdout文件描述符的进程 - 更多。这是相关的代码,我已经尝试编辑我知道有效的东西。

#define PIPE_READ 0
#define PIPE_WRITE 1
int main(int argc, char *argv[], char *envp[])
{
    int pipe_fd[3][2];
    pipe(pipe_fd[0]);
    pipe(pipe_fd[1]);
    pipe(pipe_fd[2]);

    pid[0]=fork();
    if(pid[0]==0)   /*grep-process*/
    {
        dup2(pipe_fd[0][PIPE_READ], STDIN_FILENO);
        dup2(pipe_fd[1][PIPE_WRITE], STDOUT_FILENO);
        /*close all 3 pipes, both ends, then execute grep*/
        argv[0]= "grep";
        execvp("grep",argv);
    }
    pid[1]=fork();
    if(pid[1]==0)   /*sort-process*/
    {
        dup2(pipe_fd[1][PIPE_READ], STDIN_FILENO);
        dup2(pipe_fd[2][PIPE_WRITE], STDOUT_FILENO);
        /*close all 3 pipes, both ends, then execute sort*/
        execlp("sort","sort", (char*) 0);
    }
    pid[2]=fork();
    if(pid[2]==0)   /*more-process*/
    {
        dup2(pipe_fd[2][PIPE_READ], STDIN_FILENO);
        /*close all 3 pipes, both ends, then execute more*/
        execlp("more","more", (char*) 0);
    }

    /*parent-process*/
    /*close all pipes except for the write end on the first, then write*/
       for(i=0; envp[i]!=NULL; i++)
   {
      write(pipe_fd[0][PIPE_WRITE],envp[i], strlen(envp[i]));
      write(pipe_fd[0][PIPE_WRITE],"\n",1);
   }
   close(pipe_fd[0][PIPE_WRITE]);

当然,我会检查每个调用的返回值,并且在关闭所有管道的地方,我只是写了一个注释来简化阅读。 调用./a.out PATH会导致:

INFOPATH=/usr/share/info
MANPATH=/usr/local/vol/matlab/7.4.0/man:/usr/kerberos/man:/usr/local/share/man:/
  usr/share/man/en:/usr/share/man:/usr/man
MANPATH=/usr/local/vol/matlab/7.4.0/man:/usr/kerberos/man:/usr/local/share/man:/
  usr/share/man/en:/usr/share/man:/usr/man
MODULEPATH=/usr/local/vol/modulefiles:/pkg/modules/modulefiles:/etc/site/modulef
  iles:/usr/share/Modules/modulefiles:/etc/modulefiles
MODULEPATH=/usr/local/vol/modulefiles:/pkg/modules/modulefiles:/etc/site/modulef
  iles:/usr/share/Modules/modulefiles:/etc/modulefiles
...
...

0 个答案:

没有答案