当前位置:首页>Linux>Linux system()(5)

Linux system()(5)

  • 2026-10-11 07:24:49
Linux system()(5)

Linux system()(5)

system()的一种替换方式:libexecs库

链接:

  1. 1. Manpages of libexecs-dev in Debian testing
  2. 2. virtualsquare/s2argv-execs

libexecs库和标准 C 的 system() 函数在进程创建与控制方面有本质区别。

下面是两者的主要异同点:

对比项
system()libexecs
 库
执行方式
通过 shell (/bin/sh) 执行命令字符串
直接使用 fork() + exec*() 系列函数,可绕过 shell
安全性
存在 shell 注入风险(若参数未严格过滤)
无 shell 注入风险,参数以数组或明确方式传递
控制粒度
只能等待命令结束,无法与子进程交互
可精确控制子进程的标准输入/输出/错误、环境变量、工作目录、信号等
返回值
返回命令的退出状态(经 shell 包装)
可获取子进程的精确退出码、终止信号等底层信息
错误处理
难以区分是 shell 启动失败还是命令执行失败
可清晰区分 fork/exec 各阶段的错误
异步支持
阻塞直到子进程结束(同步)
支持异步创建、非阻塞等待、管道重定向等高级模式
典型用途
简单调用外部命令或脚本
需要精细控制子进程 IO、环境、权限或避免 shell 的场景

简单示例对比

使用 system():

int system_cmdExec(const char *cmd)
{
    if
 (!cmd)
    {
        DEBUG_PRINT("error bad parameter");
        return
 -1;
    }

    if
 (0 == cmdBlackListCheck(cmd))
    {
        DEBUG_PRINT("cmd is illegal");
        return
 -1;
    }

    DEBUG_PRINT("run cmd:%s", cmd);

    int
 ret = 0;

    /* system() */

    ret = system(cmd);
    if
 ( 0 != ret)
    {
        DEBUG_PRINT("system():run cmd:%s failed, ret:%d[%d(%s)]", cmd, ret, errno, strerror(errno));
        return
 0;
    }

    DEBUG_PRINT("run cmd:%s OK", cmd);

    return
 0;
}

使用 libexecs:(其实好像有问题,不管了)

/* ref: https://manpages.debian.org/testing/libexecs-dev/ */
int
 libexecs_embedded1_cmdExec(const char *cmd)
{
    if
 (!cmd)
    {
        DEBUG_PRINT("error bad parameter");
        return
 -1;
    }

    if
 (0 == cmdBlackListCheck(cmd))
    {
        DEBUG_PRINT("cmd is illegal");
        return
 -1;
    }

    DEBUG_PRINT("run cmd:%s", cmd);

    /* TODO: exit? */

    execsp(cmd);

    DEBUG_PRINT("run cmd:%s OK", cmd);

    return
 0;
}

何时选择哪个

  • • 若只需快速调用一条简单命令且不关心安全风险,system() 足够。
  • • 若需安全地传递用户输入、重定向子进程 IO、设置环境变量、避免 shell 解析,应使用 libexecs 或类似库(如 posix_spawn、直接 fork/exec)。

如果需要查看 libexecs 的具体函数文档,可以尝试在 Debian 系统中安装 libexecs-dev 包后通过 man execs 查看,或访问其上游项目主页。

最新文章

随机文章