Chinaunix首页 | 论坛 | 博客
  • 博客访问: 426477
  • 博文数量: 184
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 594
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-17 16:24
个人简介

我是一只小小鸟

文章分类

全部博文(184)

文章存档

2016年(1)

2015年(55)

2014年(127)

2013年(1)

分类: C/C++

2014-07-09 17:04:55

[root@localhost program.c]# ls

1  1.c  2  2.c  3  3.c  4  4.c  sort.c  test1  test1.c  test.c

[root@localhost program.c]# cat 2.c 

#include

 

int main()

int i=1,sum=0;

loop: 

if(i<=100)

    { sum=sum+i;

      i++;

      goto loop;

    }

printf("sum=%d\n",sum);

 

return 211;

}

实例:判断shell脚本正常执行结束的健全代码

#include

#include

#include

#include

 

int main(void)

{

    pid_t status;

    status=system("./2");

    if(status==-1){

printf("system error\n");}

    else{

        printf("The exit status value of system function is [0x%x]\n",status);

        if(WIFEXITED(status)){

    if(WEXITSTATUS(status)==0){

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;

}

[root@localhost program.c]# gcc -Wall 4.c -o 4

[root@localhost program.c]# ./4

sum=5050

The exit status value of system function is [0xd300]

run shell script fail, script exit code: 211

1 先统一2个说法:

? system返回值:指调用system函数后的返回值,比如例中statussystem返回值

? shell返回值:指system所调用的shell命令的返回值,比如上例中,2中返回的值为shell返回值。

2 如何正确判断2是否正确执行?

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

man中对于system的说明

#man system

NAME

       system - execute a shell command

 

SYNOPSIS

       #include 

 

       int system(const char *command);

 

DESCRIPTION

       system()  executes  a  command specified in command by calling /bin/sh -c command, and

       returns after the command has  been  completed.   During  execution  of  the  command,

       SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.

system函数对返回值的处理,涉及3个阶段:

阶段1:创建子进程等准备工作。如果失败,返回-1

阶段2:调用/bin/sh拉起shell脚本,如果拉起失败或者shell未正常执行结束(参见备注1),原因值被写入到status的低8~15比特位中。systemman中只说明了会写了127这个值,但实测发现还会写126等值。

阶段3:如果shell脚本正常执行结束,将shell返回值填到status的低8~15比特位中。

 

备注1

只要能够调用到/bin/sh,并且执行shell过程中没有被其他信号异常中断,都算正常结束。

比如:不管shell脚本中返回什么原因值,是0还是非0,都算正常执行结束。即使shell脚本不存在或没有执行权限,也都算正常执行结束。

如果shell脚本执行过程中被强制kill掉等情况则算异常结束。

 

如何判断阶段2中,shell脚本是否正常执行结束呢?系统提供了宏:WIFEXITED(status)。如果WIFEXITED(status)为真,则说明正常结束。

如何取得阶段3中的shell返回值?你可以直接通过右移8bit来实现,但安全的做法是使用系统提供的宏:WEXITSTATUS(status)

 

由于我们一般在shell脚本中会通过返回值判断本脚本是否正常执行,如果成功返回0,失败返回正数。

所以综上,判断一个system函数调用shell脚本是否正常结束的方法应该是如下3个条件同时成立:

1-1 != status

2WIFEXITED(status)为真

30 == WEXITSTATUS(status)

注意:

根据以上分析,当shell脚本不存在、没有执行权限等场景下时,以上前2个条件仍会成立,此时WEXITSTATUS(status)127126等数值。

所以,我们在shell脚本中不能将127126等数值定义为返回值,否则无法区分中是shell的返回值,还是调用shell脚本异常的原因值。shell脚本中的返回值最好多1开始递增。

阅读(756) | 评论(0) | 转发(0) |
0

上一篇:《厚黑学》有感

下一篇:读文件到内存

给主人留下些什么吧!~~