我正在使用 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/