【发布时间】:2020-08-11 17:19:57
【问题描述】:
我正在编写我的 minishell,但我不明白为什么调用 pid_2 时 execve 不起作用?
我的主要任务是实现 env | grep 朗
int main(void)
{
pid_t pid_1, pid_2;
int fd[2];
int status;
char *mass_1[] = {"env", NULL};
char *mass_2[] = {"grep", "LANG", NULL};
pid_1 = fork();
pipe(fd);
if (pid_1 == 0)
{
dup2(fd[1], 0);
close(fd[0]);
execve(mass_1[0], mass_1, NULL);
exit(1);
}
pid_2 = fork();
if (pid_2 == 0)
{
dup2(fd[0], 0);
close(fd[1]);
execve(mass_2[0], mass_2, NULL);
exit(1);
}
close(fd[0]);
close(fd[1]);
waitpid(pid_1, &status, WUNTRACED);
waitpid(pid_2, &status, WUNTRACED);
return (0);
}
【问题讨论】:
-
dup2(fd[1], 0);dup2(fd[0], 0);有问题,你是dup2和0两次。他们中的一个不应该使用1与标准输出连接吗? -
pipe()在fork()之后也是错误的。这会在第一个子项中创建并使用一个单独的管道,而不是由父项创建的管道 -
env | grep LANG还将打印值中包含 LANG 的变量。有更好的方法来做到这一点。见Get list of variables whose name matches a certain pattern -
无需 fork 和运行子进程即可访问您自己进程的环境变量。如果您在 POSIX 平台上,则可以通过
extern char **environ变量直接访问整个环境变量列表。见pubs.opengroup.org/onlinepubs/9699919799/basedefs/…在Windows上,环境变量可以直接通过theGetEnvironmentStrings()function获得
标签: c