是STD ::系统或执行更好的练习

Is std::system or exec better practice?

本文关键字:更好 执行 练习 STD 系统      更新时间:2023-10-16

我有一个程序,该程序调用了我制作的shell脚本工具,该工具通过目录并汇总文件并获取chardsum值并调用其他一些工具来上传文件。该操作大约需要3至4分钟。

我这样称呼脚本:

int result = system("/bin/sh /path/to/my/script");

我也通过使用exec()功能系列获得了相同的结果:

int child = fork();
if(child == 0) {
    execl( "/bin/sh", "sh", "/path/to/my/script", (char*)0 );
}

我知道使用exec您可以将输出重定向到父程序,以便可以读取命令行工具的输出,但是除此之外,您什么时候应该使用system而不是exec

暂时忽略system的使用是可移植的,而使用exec函数家族不可移植...

当您将exec功能系列的使用与其他POSIX函数(例如pipedupwait(结合在一起时,您将获得更多控制如何在父过程和子过程之间传递数据的控制。

当您不需要任何这些控件时,即您只想执行命令,那么使用system是优选的,IMO。

您的问题中的第一个system调用将做同样的事情,您在下一个代码(fork and execl(中所做的事情

来自文档:

 The system() library function uses fork(2) to create a child process
 that executes the shell command specified in command using execl(3)

http://man7.org/linux/man-pages/man3/system.3.html