linux c system结束进程,linux c system返回值问题总结

先看例子shell

d61263c1bee04cd69549cc80.html

d61263c1bee04cd69549cc80.html

#include #include#include#include

intmain()

{

pid_t status;

status= system("./test.sh");if (-1 ==status)

{

printf("system error!");

}else{

printf("exit status value = [0x%x]\n", status);//status 低7bits表示致使任务退出的信号数值,右起第8bit表示是否生成coredump文件;//高8位是实际的exit参数值。宏的时间参见标注c头文件

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 //错误退出,这里属于信号中断了,WEXITSTATUS必定是0了

{

printf("exit status = [%d]\n", WEXITSTATUS(status));

}

}return 0;

}

View Code

下面更详细解释:安全

一、先统一两个说法:ide

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

(2)shell 返回值:指system所调用的shell命令的返回值,好比上例中,test.sh中返回的值为shell返回值。spa

二、如何正确判断test.sh是否正确执行?code

都错!(仅仅判断status是否==0?或者仅判断status是否!=-1? )orm

三、man中对于system的说明blog

RETURN VALUE进程

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

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).

看得很晕吧?

四、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过程当中没有被其余信号异常中断,都算正常结束。

好比:

无论shell脚本中返回什么缘由值,是0仍是非0,都算正常执行结束。即便shell脚本不存在或没有执行权限,也都算正常执行结束。

若是shell脚本执行过程当中被强制kill掉等状况则算异常结束。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值