Linux中system函数返回值详解

来源:互联网 发布:pdf电子书资源 知乎 编辑:程序博客网 时间:2024/05/29 03:26

描述

system()库函数使用fork(2)创建一个子进程,该子进程使用execl(3)执行指定的shell命令,

execl(“/bin/sh”, “sh”, “-c”, command, (char *) 0);

头文件

system - execute a shell command#include <stdlib.h>int system(const char *command);

返回值 

  • 如果子进程无法创建,或者其状态不能被检索,则返回值为-1;
  • 如果在子进程中不能执行一个shell,或shell未正常的结束,返回值被写入到status的低8~15比特位中;一般为127值
  • 如果所有系统调用都成功, 将shell返回值填到status的低8~15比特位中

系统宏

  • 系统中提供了两个宏WIFEXITED(status)、WEXITSTATUS(status)判断shell的返回值

    • WIFEXITED(status) 用来指出子进程是否为正常退出的,如果是,它会返回一个非零值
    • WEXITSTATUS(status) 用来获取返回值status的低8~15数据

有了这两个宏代码就简介很多, 总结一下,system的返回值需要通过以下三个步骤确定

  • 首先判断子进程是否成功, status != -1;
  • 判断子进程是否正常退出, WIFEXITED(status)是否非零;
  • 子进程的返回值, WEXITSTATUS(status) == 0 ;
#include<stdio.h>#include<string.h>#include<stdlib.h>int main(){    pid_t status;     status = system("./test.sh");    printf("exit status value = [0x%x]\n", status);    if (WIFEXITED(status))    {        if (0 == WEXITSTATUS(status))        {            printf("run sucess\n");        }        else        {            printf("run fail, exit code: %d\n", WEXITSTATUS(status));        }    }    else    {        printf("exit status = [%d]\n", WEXITSTATUS(status));    }}

参考

  • 通过system返回值判断 命令是否正确执行
  • Linux system函数返回值
  • 父进程等待子进程终止 wait, WIFEXITED, WEXITSTATUS