gpt4 book ai didi

c - 使用 execvp 执行 grep,从管道读取

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:31 25 4
gpt4 key购买 nike

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


}
}

最佳答案

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

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

关于c - 使用 execvp 执行 grep,从管道读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20129328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com