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