有些时候我们不得不使用系统调用system来执行shell脚本,而且还需要知道是否执行成功,下面就介绍怎么判断时候成功执行。
例:
1. status = system("./test.sh");
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 commandotherwise. 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 thatdoes exit(127).
看得很晕吧?
system函数对返回值的处理,涉及3个阶段: