c - c 中的 Exec 函数在应该返回 -1 时没有返回

标签 c fork exec

我正在使用 execv 函数来运行名为 code.x 的程序。 code.x 有一部分通过断言保证其失败。 我运行 execl 的代码是:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h> 
#include <errno.h>
#include <string.h>

int main()
{
    pid_t pid;
    char *args[] = { "./code.x",NULL };
    pid = fork();
    if (pid > 0) {
        wait(NULL);
        printf("%s\n", strerror(errno));
        printf("done\n");
    }
    else if (pid == 0) {
        printf("%s\n", strerror(errno));
        execv(args[0], args);
        printf("should fail");
    }
    else {
        printf("forkfail");
    }
    return 1;
}

代码打印

Success
code.x: code.c:15: main: Assertion '0 == 1' failed.
Success
done

“should fail”从不打印,WEXITSTATUS(status) 显示退出状态为 0。

最佳答案

exec 函数族用从可执行文件加载的处于初始状态的新程序替换调用进程。它们只有在替换失败时才会失败,例如由于请求的文件不存在或调用用户无权访问/执行它。

如果您正在调用的程序 ./code.x 中发生断言失败,那么这早已超过了 execv 可能失败的程度;此时,原来执行execv的程序状态已经不存在了,因为它已经被替换了。父进程将通过 wait-family 函数看到它退出,并且可以检查 wait-family 函数报告的状态以确定它退出的原因。

关于c - c 中的 Exec 函数在应该返回 -1 时没有返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53511285/

相关文章:

c++ - cin.tellg 在从管道接收输入时返回 -1

c - 如何正确使用startup-ipi来启动应用处理器?

c - 寻找一种快速轮廓线渲染算法

C - 无法释放分配的内存

c - 命名管道,使用 Fork()

php - 从 PHP 运行 Python 脚本

c++ - 使用 C++ 编译器时遇到错误 "type qualifier specified more than once"

c - 两个进程读取相同的标准输入

C - 多个进程写入同一个日志文件

perl - 这条线到底是做什么的,它是如何做到的?打开我的 $fh_echo, '-|' 或 exec "$sshstr\"$str\""