gpt4 book ai didi

c - 如何阻止 execve 退出原始程序

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

我已经编写了自己的 shell 并编写了一个处理三重管道的函数,但是我的 shell 在 execve 之后退出时遇到了问题。我认为问题是我需要多花点时间?但我不完全确定在哪里,因为这可以完美地执行管道程序。此实现中也没有使用 wait(2),不确定这是否也与它有关。谢谢

int fd[2];
int fd2[2];

if (pipe(fd) == -1)
{
perror("ERROR CREATING PIPE");
return;
}

pid_t pid = fork();

if (args4[0] != NULL)
{
switch(pid)
{
case -1:
printf("%s\n", "fail to fork");
return;
case 0:
if (pipe(fd2) == -1)
{
perror("ERROR CREATING PIPE");
return;
}
switch(pid = fork())
{
case -1:
printf("%s\n", "fail to fork");
return;
break;
case 0:
if ( dup2(fd2[1], STDOUT_FILENO) == -1 )
{
printf("%s\n", "fail to dup");
return;
}
close(fd2[0]);
close(fd2[1]);
execve(args2[0], args2, environ);
exit(1);
default:
if ( dup2(fd2[0], STDIN_FILENO) == -1 )
{
printf("%s\n", "fail to dup");
return;
}
if ( dup2(fd[1], STDOUT_FILENO) == -1 )
{
printf("%s\n", "fail to dup");
return;
}
close(fd2[0]);
close(fd2[1]);
execve(args3[0], args3, environ);
exit(2);
}
exit(3);

default:
if ( dup2(fd[0], STDIN_FILENO) == -1)
{
printf("%s\n", "fail to dup");
return;
}
close(fd[0]);
close(fd[1]);
printf("%s\n", "4");
execve(args4[0], args4, environ);
exit(4);
}
}

最佳答案

你 fork 了两次,所以你有 3 个进程。它们中的每一个都被 execve 创建的相应进程替换。你永远不会到达 exit() 语句,因为 execve() 不返回(成功时)。这是您在没有管道的情况下重写的代码(您清楚地了解如何设置管道)并且没有不必要的语句:

pid_t pid = fork();
if (pid) {
execve(args4[0], args4, environ);
}
else {
pid = fork();
if (pid) {
execve(args3[0], args3, environ);
}
else {
execve(args2[0], args2, environ);
}
}

通过上面重写的代码,您可以更容易地看到您将获得如下三个进程:

参数2[0] | args3[0] | arg4[0]

关于c - 如何阻止 execve 退出原始程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43151478/

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