c - 执行返回-Ubuntu

标签 c ubuntu exec

我的问题是:新进程镜像执行完成后,函数

execl()

将执行返回给调用者进程还是父进程?

最佳答案

当使用 exec 函数族之一时,您根本不希望函数返回。程序计数器从替换调用进程的二进制镜像的第一条指令开始。

来自 Darwin 手册页:

If any of the exec() functions returns, an error will have occurred. The return value is -1, and the global variable errno will be set to indicate the error.

有一条评论询问以下内容,但已被删除:

如果您在子进程中,并且 execl 成功,则子进程将被新的二进制文件替换。如果失败,则控制返回到该子进程(调用者)。 forkexec 之间没有严格的关系,如果那是您要问的。如果您在子进程中,并且 exec 失败,则您有一个“ fork 的”子进程,它是原始父进程的副本。此时您可能想要打印一些错误消息并退出子进程。

如果您想知道失败的原因,可以使用以下模式:

if (execl(...)) {
    perror(NULL);
    exit(errno);
}

例如,尝试运行这个程序,错误信息会指出如何修复这个程序:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (const int argc, char * const argv[]) {
    if (execl("ls", "ls", "-la", NULL)) {
        perror(NULL);
        exit(errno);
    }

    return 0;
}

解决方案,在这种情况下使用execlp 而不是execl

关于c - 执行返回-Ubuntu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25598046/

相关文章:

php - FFMPEG 在命令行中工作,但不能在 exec() 中工作,它返回 127

c++ - 有没有实现的说话人识别算法

python - gtk+ 复选按钮设置

c - 快板5游戏: game loop that runs at constant speed?

c - 将 2D 数组存储在 3D 数组中

php - 完全删除 phpMyAdmin

Kotlin native - 执行可执行文件

c++ - fork() 之后如何处理 execvp(...) 错误?

c - OpenGL 编译错误 Ubuntu

linux - 如何将url重定向到根文件夹