Linux c system返回值

这篇文章详细解释了C程序如何使用`system()`函数执行shell脚本,并通过`fork()`和`WIFEXITED()`检查脚本的执行状态,包括正常结束、异常结束以及错误处理的情况。
摘要由CSDN通过智能技术生成
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) 
{
    pid_t status;
    status = system("ls");

    if (-1 == status)  //fork fail
    {
        printf("system error!");
    }
    else
    {
        printf("exit status value = [%d]\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;
}

调用/bin/sh拉起shell脚本,如果拉起失败或者shell未正常执行结束(参见备注1),原因值被写入到status的低8~15比特位中。
只要能够调用到/bin/sh,并且执行shell过程中没有被其他信号异常中断,都算正常结束。
比如:不管shell脚本中返回什么原因值,是0还是非0,都算正常执行结束。即使shell脚本不存在或没有执行权限,也都算正常执行结束。
如果shell脚本执行过程中被强制kill掉等情况则算异常结束。
WIFEXITED(status) 若此值为非0 表明进程正常结束

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值