system 函数的正确使用

1、system 的正确使用

由于程序中我们可以通过 system() 调用标准的 shell 命令(成功返回 0)可以减少很多繁琐的细节。

bool root_exec_cmd(char * cmd_buf)
{
    int status;
    bool exec_switch = false;
    int32_t oldUid = getuid();
    if(setuid(0) != 0) // 获取 root 权限
    {
        LOGE("get root permision fail [%s]",strerror(errno));
        return false;
    }
    status = system(cmd_buf); // 创建子进程等准备工作。如果失败,返回-1。
    if(-1 == status)
    {
        LOGD("exec cmd [ %s ] create child process fail [%s]",cmd_buf,strerror(errno));
        exec_switch = false;
    }else {
        if (WIFEXITED(status))  // 调用/bin/sh拉起shell脚本,如果拉起失败或者shell未正常执行结束,如果WIFEXITED(status)为真,则说明正常结束。
        {
            if (0 == WEXITSTATUS(status))  // 这里判断 执行的 cmd 的返回值
            {
                LOGD("shell cmd [%s] exec success",cmd_buf);
                exec_switch = true;
            }else {
                LOGD("run shell cmd [%s] fail, error code: %d, error info [%s] ", cmd_buf , WEXITSTATUS(status), strerror(WEXITSTATUS(status)));
                exec_switch = false;
            }
        }else {
            LOGD("[%s] child process abnormal exit  ", cmd_buf);
            if(WIFSIGNALED(status))
            {
                LOGD("abnormal exit signal: %d ", WTERMSIG(status));
            }else if(WIFSTOPPED(status))
            {
                LOGD("stop exec signal : %d ",WSTOPSIG(status));
            }else {
                LOGD("unknow signal ...");
            }
            exec_switch = false;
        }
    }
    if(exec_switch == true)
    {
        if(setuid(oldUid) != 0)
        {
            LOGE("restore hostUpdate permision fail [%s]",strerror(errno));
            return false;
        }
        return true;
    }else {                                                                                                                                                                                                                                                                                                                  
        if(setuid(oldUid) != 0)
        {
            LOGE("restore hostUpdate permision fail [%s]",strerror(errno));
            return false;
        }
        return false;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值