描述
C 库函数 int system(const char *command) 把 command 指定的命令名称或程序名称传给要被命令处理器执行的主机环境,并在命令完成后返回。
声明
下面是 system() 函数的声明。
#include
int system(const char *command)
参数
command – 包含被请求变量名称的 C 字符串。
返回值
如果发生错误,则返回值为 -1,否则返回命令的状态。
实例
#include
#include
#include
int main () {
char command[50]; strcpy( command, "ls -l" ); system(command); return(0); }
WIFEXITED/WEXITSTATUS函数
systerm两层含义
1、正确退出后。还需要再判断,操作成功或者操作失败。
2、错误退出。
函数实例
#include
#include
#include
#include
int main() {
pid_t status; status = system("./test.sh"); if (-1 == status) {
printf("system error!"); } else {
printf("exit status value = [0x%x]\n", status); if (WIFEXITED(status)) //正确退出 {
if (0 == WEXITSTATUS(status)) //操作成功 {
printf("run shell script successfully.\n"); } else //操作失败 {
printf("run shell script fail, script exit code: %d\n", WEXITSTATUS(status)); } } else //错误退出 {
printf("exit status = [%d]\n", WEXITSTATUS(status)); } } return 0; }
详解解释
1、先统一两个说法:
2、如何正确判断test.sh是否正确执行?
都错!(仅仅判断status是否==0?或者仅判断status是否!=-1? )
3、man中对于system的说明
4、system函数对返回值的处理。
阶段1:
创建子进程等准备工作。如果失败,返回-1。
阶段2:
阶段3:
备注1:
只要能够调用到/bin/sh,并且执行shell过程中没有被其他信号异常中断,都算正常结束。
比如:
参考资料
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/209762.html原文链接:https://javaforall.net
