zoukankan      html  css  js  c++  java
  • system函数


    system两层含义:

    1、正确退出后。还需要再判断,操作成功或者操作失败。

    2、错误退出。

    #include <stdio.h>  
    #include <stdlib.h>  
    #include <sys/wait.h>  
    #include <sys/types.h>  
      
    int main()  
    {  
        pid_t status;  
      
        status = system("./test.sh");  
      
        if (-1 == status)  
        {  
            printf("system error!");  
        }  
        else  
        {  
            printf("exit status value = [0x%x]
    ", status);  
      
            if (WIFEXITED(status))  //正确退出
            {  
                if (0 == WEXITSTATUS(status)) //操作成功
                {  
                    printf("run shell script successfully.
    ");  
                }  
                else  //操作失败
                {  
                    printf("run shell script fail, script exit code: %d
    ", WEXITSTATUS(status));  
                }  
            }  
            else  //错误退出
            {  
                printf("exit status = [%d]
    ", WEXITSTATUS(status));  
            }  
        }  
      
        return 0;  
    }


    下面更详细解释:

    1、先统一两个说法:

    (1)system 返回值:指调用system函数后的返回值,比如上例中status为system返回值

    (2)shell 返回值:指system所调用的shell命令的返回值,比如上例中,test.sh中返回的值为shell返回值。
    2、如何正确判断test.sh是否正确执行?

    都错!(仅仅判断status是否==0?或者仅判断status是否!=-1? )
    3、man中对于system的说明

    RETURN VALUE

           The value returned is -1 on error (e.g.  fork() failed), and the return

           status  of  the command otherwise.  This latter return status is in the

           format specified in wait(2).  Thus, the exit code of the  command  will

           be  WEXITSTATUS(status).   In  case  /bin/sh could not be executed, the

           exit status will be that of a command that does exit(127).

    看得很晕吧?
    4、system函数对返回值的处理。

    阶段1:
    创建子进程等准备工作。如果失败,返回-1。
    阶段2:
    调用/bin/sh拉起shell脚本,如果拉起失败或者shell未正常执行结束(参见备注1),原因值被写入到status的低8~15比特位中。

    如何判断阶段2中,shell脚本是否正常执行结束呢?系统提供了宏:WIFEXITED(status)。如果WIFEXITED(status)为真,则说明正常结束。
    阶段3:
    如果shell脚本正常执行结束,将shell返回值填到status的低8~15比特位中。

    如何取得阶段3中的shell返回值?你可以直接通过右移8bit来实现,但安全的做法是使用系统提供的宏:WEXITSTATUS(status)。
    备注1:
    只要能够调用到/bin/sh,并且执行shell过程中没有被其他信号异常中断,都算正常结束。
    比如:

    参考链接:http://www.embeddedlinux.org.cn/emb-linux/system-development/201310/10-2635.html

  • 相关阅读:
    《人工智能的下一个挑战 —— 可解释性和可诠释性?》
    《python源码剖析-字节码和虚拟机》
    PP生产订单成本的计划、控制和结算
    存货核算当期单价(调整当期存货单价)
    财务审计核算单价
    成本核算过程
    WMS与MES集成
    月初一次冲回与单到冲回的理解
    财务结算的目的和一般流程
    ERP启动会
  • 原文地址:https://www.cnblogs.com/klcf0220/p/5783826.html
Copyright © 2011-2022 走看看