用execvp执行grep,从管道读取

时间:2013-11-21 18:40:40

标签: c grep exec pipe execvp

我试图模仿shell命令行的功能:

printenv |grep VISUAL

通过创建子进程,在其中执行grep,并从父函数将环境变量写入连接到grep的管道。但这并不起作用; grep函数会继续打印我写入的所有内容(无论字符串是grep)。这是代码(我删除了错误代码的检查和处理):

#define PIPE_READ 0
#define PIPE_WRITE 1
pid_t pid;


int main(int argc, char *argv[], char *envp[])
{
   int pipe_fd[2];
   int return_value, status;
       return_value=pipe(pipe_fd);
       pid=fork();
    if(pid==0)
    {
        dup2(pipe_fd[PIPE_READ], STDIN_FILENO); /*Grep should read from pipe*/
        close(pipe_fd[PIPE_READ]);
        close(pipe_fd[PIPE_WRITE]);
        char *arg_list[] = {"grep", "VISUAL",NULL};
        execvp("grep", arg_list); /*here somewhere is where I think the problem 
  lies, although I've tried everything here. The first argument is the command to
  execute, the second is the name of it again, the thirt should be the string to 
  search for and a file is optional, if there's no file it should read from 
  stdin (the pipe).*/
     }

     else /*parent process*/
     {
         close(pipe_fd[PIPE_READ]);
         int i;
                     /*Write the environment variables to the pipe.*/
         for(i=0; envp[i]!=NULL; i++)
         {
            write(pipe_fd[PIPE_WRITE],envp[i], strlen(envp[i]));
         }
         close(pipe_fd[PIPE_READ]);


     }
}

1 个答案:

答案 0 :(得分:3)

一个明显的问题是你没有把换行写入管道,这意味着如果你写的整个字符串中有任何东西匹配,grep将输出整个字符串,因为它只有一行。尝试在第一次写入后添加第二次写入:

write(pipe_fd[PIPE_WRITE],"\n",1);