Linux system函数返回值

来源:互联网 发布:sql注入攻击实例 编辑:程序博客网 时间:2024/05/17 06:51

[cpp]
 view plaincopy
  1. status = system("./test.sh");  
文章转载来自于:http://blog.chinaunix.net/uid-24774106-id-3048281.html?page=3
http://blog.csdn.net/cheyo/article/details/6595955

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)
.
看得很晕吧?

system函数对返回值的处理,涉及3个阶段:
阶段1:创建子进程等准备工作。如果失败,返回-1。
阶段2:调用/bin/sh拉起shell脚本,如果拉起失败或者shell未正常执行结束(参见备注1),原因值被写入到status的低8~15比特位中。system的man中只说明了会写了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
(2)WIFEXITED(status)为真
(3)0 == WEXITSTATUS(status)

注意:
根据以上分析,当shell脚本不存在、没有执行权限等场景下时,以上前2个条件仍会成立,此时WEXITSTATUS(status)为127,126等数值。
所以,我们在shell脚本中不能将127,126等数值定义为返回值,否则无法区分中是shell的返回值,还是调用shell脚本异常的原因值。shell脚本中的返回值最好多1开始递增。

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

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <sys/wait.h>  
  4. #include <sys/types.h>  
  5.   
  6. int main()  
  7. {  
  8.     pid_t status;  
  9.   
  10.   
  11.     status = system("./test.sh");  
  12.   
  13.     if (-1 == status)  
  14.     {  
  15.         printf("system error!");  
  16.     }  
  17.     else  
  18.     {  
  19.         printf("exit status value = [0x%x]\n", status);  
  20.   
  21.         if (WIFEXITED(status))  
  22.         {  
  23.             if (0 == WEXITSTATUS(status))  
  24.             {  
  25.                 printf("run shell script successfully.\n");  
  26.             }  
  27.             else  
  28.             {  
  29.                 printf("run shell script fail, script exit code: %d\n", WEXITSTATUS(status));  
  30.             }  
  31.         }  
  32.         else  
  33.         {  
  34.             printf("exit status = [%d]\n", WEXITSTATUS(status));  
  35.         }  
  36.     }  
  37.   
  38.     return 0;  
  39. }  

WIFEXITED(stat_val) Evaluates to a non-zero value if status
was returned for a child process that
terminated normally.

WEXITSTATUS(stat_val) If the value of WIFEXITED(stat_val) is
non-zero, this macro evaluates to the
low-order 8 bits of the status argument
that the child process passed to _exit()
or exit(), or the value the child
process returned from main().



  1. #include <stdlib.h>

  2. int system(const char *command);
    system的作用是在shell终端执行command。简单的说就是在C中执行system("ls")这行代码的含义就相当于在shell执行ls一样。这么说还是比较笼统,下面详细描述之:

    system是个综合的操作,分解开来看就是相当于执行了
1 fork  生成一个子进程。
2 在子进程执行 execl("/bin/sh","sh","-c" command,(char*)0);
3 waitpid

下面进入正题,返回值:
1 如果fork失败了,或者waitpid返回除了EINTR之外的错误,system返回 -1;
2 execl执行失败,其返回值如同shell执行了"exit(127)" 一样。
3 如果上述三步都执行成功,那么,system返回值是shell的终止状态。


上面这些话是APUE的,很抽象,很不具体,很笼统,我现在结合手册和代码解释一下。

手册中有这么一段话:
  1. The value returned is -1 on error (e.g. fork(2) 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
  2.  exit(127).
1 如果/bin/sh拉起shell命令失败,或者是shell命令没有正常执行 (比如命令根本就是非法的命令),那么,将原因填入status的8~15位。
  手册中也说如果命令执行不起来,那么相当于执行exit
  1. libin@libin:~/program/C/Linux/system$ ./tsys "nosuchcmd"
  2. sh: nosuchcmd: not found
  3. status = 32512
  4. normal termination,exit status = 127
我们看到了,nosuchcmd不是shell支持的命令,所以,shell命令返回了127,对于system函数,返回值为127*256 = 32512;因为shell的返回值是 system返回值的8~15位。

2  如果shell顺利执行完毕,那么将shell的返回值填到system返回值的8~15位。
 这里需要强调以下,所谓顺利执行完毕,并不是说,命令command执行成功,而是指  /bin/sh顺利调用,执行期间没有被信号异常终止,这都算是顺利执行完毕。
  
看下面的例子:

  1. libin@libin:~/program/C/Linux/system$ ./tsys "ls /noexisted"
  2. ls: 无法访问/noexisted: 没有那个文件或目录
  3. status = 512
  4. normal termination,exit status = 2

  5. libin@libin:~/program/C/Linux/system$ ls /noexist
  6. ls: 无法访问/noexist: 没有那个文件或目录
  7. libin@libin:~/program/C/Linux/system$ echo $?
  8. 2
  9. libin@libin:~/program/C/Linux/system$ 
    我们看到了,虽然/noexist文件并不存在,ls这条命令执行出了错,但是仍然属于shell顺利执行完毕。ls /noexist的错误吗是2,所以,system函数的返回值为 2*256 = 512.

    各位可能比较感兴趣的是,如果我知道system的返回值,如何知道我的命令的返回值呢?手册中有这么一句话:
  1. Thus, the exit code of the command will be WEXITSTATUS(status)
    看到了WEXITSTATUS(status),就是command的返回值。当然前提条件是shell命令顺利执行完毕。即
  1. WIFEXITED(status) ! =0

3 前面的讨论都没有考虑信号,如果shell在执行过程中收到了信号。
这个问题我存在有疑惑,因为APUE第十章讲到,system的实现要忽略SIGINT和SIGQUIT,但是我的实验结果并不是这样,如有高手知道,请不吝赐教。

首先看我的终端信号配置:
  1. libin@libin:~/program/C/Linux/system$ stty -a
  2. speed 38400 baud; rows 36; columns 134; line = 0;
  3. intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = M-^?; eol2 = M-^?; swtch = M-^?; start = ^Q; stop = ^S; susp = ^Z;
  4. rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
  5. -parenb -parodd cs8 hupcl -cstopb cread -clocal -crtscts
  6. -ignbrk brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc ixany imaxbel iutf8
  7. opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
  8. isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke
    Ctrl+C产生SIGINT,Ctrl+\ 产生 SIGQUIT。
    看下测试结果
  1. libin@libin:~/program/C/Linux/system$ ./tsys "sleep 7"
  2. ^Cstatus = 2
  3. abnormal termination,signal number =2
  4. libin@libin:~/program/C/Linux/system$ sleep 7
  5. ^C
  6. libin@libin:~/program/C/Linux/system$ echo $?
  7. 130
    我们可以看到,直接在终端执行sleep 7,然后用Ctrl+C发送SIGINT信号,异常退出,shell返回值为130,130的原因,APUE上解释了,因为SIGINT 等于2,终止状态是128+信号编号,所以为130.

    按照APUE上,我们的system调用应该将SIGINT忽略掉,然后正常返回,同时返回值为130,但是实际上LINUX下并不是这样的。实际上system的返回值为2,并且异常退出了。

    SIGQUIT信号也是一样的,看我在我的Ubuntu 上做的测试:
  1. libin@libin:~/program/C/Linux/system$ ./tsys "sleep 7"
  2. ^\status = 3
  3. abnormal termination,signal number =3
  4. libin@libin:~/program/C/Linux/system$ sleep 7
  5. ^\退出
  6. libin@libin:~/program/C/Linux/system$ echo $?
  7. 131

    2012年1月1日,我做了下面的实验测试,下面是实验的过程。
  1. root@libin:~/program/C/Linux/system# ./tsys "sleep 50" &
  2. [1] 2518
  3. root@libin:~/program/C/Linux/system# ps -ef


  4. root 2359 2343 0 12:42 pts/0 00:00:00 /bin/bash
  5. root 2518 2359 0 12:55 pts/0 00:00:00 ./tsys sleep 50
  6. root 2519 2518 0 12:55 pts/0 00:00:00 sh -c sleep 50
  7. root 2520 2519 0 12:55 pts/0 00:00:00 sleep 50
  8. root 2521 2359 0 12:56 pts/0 00:00:00 ps -ef
  9. root@libin:~/program/C/Linux/system# kill -3 2520
  10. Quit
  11. status = 33536
  12. normal termination,exit status = 131


  13. root@libin:~/program/C/Linux/system# ./tsys "sleep 50" &
  14. [1] 2568
  15. root@libin:~/program/C/Linux/system# ps -ef

  16. root 2568 2359 0 13:01 pts/0 00:00:00 ./tsys sleep 50
  17. root 2569 2568 0 13:01 pts/0 00:00:00 sh -c sleep 50
  18. root 2570 2569 0 13:01 pts/0 00:00:00 sleep 50
  19. root 2571 2359 0 13:01 pts/0 00:00:00 ps -ef
  20. root@libin:~/program/C/Linux/system# kill -3 2569
  21. status = 3
  22. abnormal termination,signal number =3
 
    从测试结果上看,基本上进程关系如下,system的返回值,其实是shell的终止状态,
而不是sleep的返回值。所谓屏蔽INTR信号和QUIT信号,指的是tsys这个进程,忽略了INT信号的QUIT信号,但是sh进程,和sleep进程,都没有忽略这两个信号。

    如果给sleep进程发送SIGQUIT信号,杀死sleep进程,那么sleep会返回131,告诉shell进程我被SIGQUIT杀死了。而sh进程,则是安然退出,所以,依然打印出正常退出的打印,通过调用WEXITSTATUS,看以看出,sleep进程的遗言是131,表明收到QUIT信号。


    下面是测试程序,基本是照抄的APUE。
  1. #define _XOPEN_SOURCE

  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<unistd.h>

  5. #include<signal.h>
  6. #include<sys/wait.h>

  7. void pr_exit(int status)
  8. {
  9.         printf("status = %d\n",status);
  10.     if(WIFEXITED(status))
  11.         {
  12.          printf("normal termination,exit status = %d\n",WEXITSTATUS(status));
  13.         }

  14.         else if(WIFSIGNALED(status))
  15.         {
  16.          printf("abnormal termination,signal number =%d%s\n",
  17.                                 WTERMSIG(status),
  18. #ifdef WCOREDUMP
  19.                                 WCOREDUMP(status)?"core file generated" : "");
  20. #else
  21.                 "");
  22. #endif
  23.         }
  24. }


  25. int main(int argc,char* argv[])
  26. {
  27.         int status;

  28.         if(argc<2)
  29.         {
  30.          fprintf(stderr,"usage:tsys cmd\n");
  31.                  return -1;
  32.         }

  33.         if((status = system(argv[1]) )<0)
  34.         {
  35.          fprintf(stderr,"system error\n");
  36.                 return -2;
  37.         }

  38.         pr_exit(status);
  39.     return 0;
  40. }
0 0
原创粉丝点击