c - 调用exec后子进程会发生什么?

标签 c fork exec

我是系统编程的新手,很好奇 exec 函数的工作原理。我的第一个问题是为什么 child 在调用 exec 后从不打印“我是 child ”。 exec如何替换子进程?我的第二个问题是为什么程序(在调用 exec 之后)在完全终止之前继续并要求再提供一个命令行参数。我不确定这里发生了什么。任何人都可以解释发生了什么,将不胜感激。这是代码:

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

int main(void) {

    if(fork() == 0){
        printf("Hello from child!\n");
        execl("/usr/bin/sort", "sort", "talk.c",NULL);
        printf("I'm the child\n");
    }
    else{
        printf("Hello from parent!\n");
        printf("Iam the parent\n");
    }
    return 0;
}

最佳答案

您可以在 https://linux.die.net/man/3/execl 中阅读有关 execl 的信息

The exec() family of functions replaces the current process image with a new process image. The functions described in this manual page are front-ends for execve(2). (See the manual page for execve(2) for further details about the replacement of the current process image.)

exec 系列将当前进程镜像替换为新进程镜像,因此 execl 之后不会发生任何事情。

关于c - 调用exec后子进程会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55828193/

相关文章:

c - C 程序员的算法和数据结构实现

c++ - 如何提供链接时找不到的功能?

在 C 中计算 ICMPv6 数据包的校验和

c - 为什么我的代码中的 fork() 函数没有创建子进程?

c++ - 来自::popen() 的 ENOMEM 的原因

c - fork() 并写入命令

ruby - 如何在远程计算机上的 Ruby ssh exec 上强制执行持续时间或超时

c - 给定函数 `decode` ,我如何进行逆运算并将函数写入 `encode` ?

Linux 用户态执行

php - 如何修复使用PHP运行的ffmpeg中的 "Unable to find a suitable output format for '/'"错误