Domin1c0's Blog

A technical blog sharing my journey in programming, development, and open source.

View on GitHub
22 July 2025

exec

by

exec 函数族

如果想在一个进程内部执行系统命令或者是应用程序,优先应该想到如下方式:

exec 函数是用一个新程序替换了当前进程的代码段、数据段、堆和栈;原有的进程间没有变化,没有创建新的进程,进程PID没有发生变化

execl

一般用于执行用户自定义的应用程序

int execl(const char *path, const char *arg0, ..., (char *)NULL)

代码示例

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

int main()
{
    printf("Using execl to run /bin/ls:\n");

    // 替换当前进程,执行 /bin/ls -l /
    execl("/bin/ls", "ls", "-l", "/", (char *)NULL);

    // 如果 exec 返回,说明出错了
    perror("execl failed");
    return 1;
}

execlp

一般用于执行系统命令

int execlp(const char *file, const char *arg0, ..., (char *)NULL);
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() 
{
    printf("Using execlp to run ls:\n");

    // 不写 /bin/ls,直接写 "ls" 让系统自动查找
    execlp("ls", "ls", "-a", (char *)NULL);

    // 如果失败
    perror("execlp failed");
    return 1;
}

tags: 进程 - 进程相关函数