Linux system()(5)
system()的一种替换方式:libexecs库
链接:
- 1. Manpages of libexecs-dev in Debian testing
- 2. virtualsquare/s2argv-execs
libexecs库和标准 C 的 system() 函数在进程创建与控制方面有本质区别。
下面是两者的主要异同点:
| system() | libexecs |
|---|
| 执行方式 | 通过 shell (/bin/sh) 执行命令字符串 | 直接使用 fork() + exec*() 系列函数,可绕过 shell |
| 安全性 | | 无 shell 注入风险,参数以数组或明确方式传递 |
| 控制粒度 | | 可精确控制子进程的标准输入/输出/错误、环境变量、工作目录、信号等 |
| 返回值 | | |
| 错误处理 | | |
| 异步支持 | | |
| 典型用途 | | 需要精细控制子进程 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 查看,或访问其上游项目主页。