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

标签 c io pipe fork io-redirection

我已经编写了自己的 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/

相关文章:

java - 如何将 XMLStreamReader 转换为 XMLStreamWriter

c - C 的单元测试框架

c - 如何显示数组

c++ - (c/c++) 字符串文字的拷贝是否在 TEXT 部分共享内存?

bash - 最小化 bash 中延迟循环处理的缓冲管道

linux - 如何使用管道进行非阻塞 IPC(UART 仿真)

java - 将 Java 管道传输到 Grep : Why not working?

javascript - 将 C 可执行文件与 html 集成

c++ - Radeon 卡是否可以从 DisplayPort 读取数据(使用 OpenCL)?

java - 如何正确分隔一个字符