1

我正在尝试模仿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]);


     }
}
4

1 回答 1

3

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

write(pipe_fd[PIPE_WRITE],"\n",1);
于 2013-11-21T19:03:41.907 回答