分类: LINUX
2011-07-14 08:49:44
刚用到system函数,要根据其返回值来做进一步操作,可是system的返回值并不等于其调用的程序的返回值,man了没看懂,后来在网上搜索了一下,终于看到了一个DX的理解,记录之。
引自:原文
要分成两部分来说:
1,在程序中,用exit来设置进程的退出值时,虽然该函数的参数类型为int型,但再父进程中只能取到其值的低8位.所以用exit返回值时,高于255的值是没有意义的.
2,对于system函数,返回值是由两部分组成的,低8位值表示所执行的脚本在执行过程中所接收到的信号值,其余的位表示的脚本exit退出时所设置的值
测试代码:u'V0O a-G0K&^f
#include
int main()
{
int ret;
ret = system("exit 0");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 1");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 2");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 3");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 4");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 5");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 6");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 7");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 8");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 9");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 10");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 11");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 12");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 13");
printf("ret%d ret%d\n",ret,ret/256);
ret = system("exit 14");
printf("ret%d ret%d\n",ret,ret/256);
}
ret0 ret0
ret256 ret1
ret512 ret2
ret768 ret3
ret1024 ret4
ret1280 ret5
ret1536 ret6
ret1792 ret7
ret2048 ret8
ret2304 ret9
ret2560 ret10
ret2816 ret11
ret3072 ret12
ret3328 ret13
ret3584 ret14
如果还不放心请看下面的代码:
包含文件
#include
#include
#include
先写一个被调用的函数
==================================
#include
int main()
{
printf("Return 10./n");
return 10;
}
==================================
编译后生成一个"rt"的可执行文件
运行结果
==================================
Return 10.
==================================
再写一个调用system的程序
==================================
#include
#include
#include
#include
int main()
{
pid_t status ;
int errno = 0 ;
status = system("./rt") ;
printf("wifexited(status):%d/n",WIFEXITED(status));
printf("WEXITSTATUS(status):%d/n",WEXITSTATUS(status));
if (status == -1)
printf("system error!") ;
if (WIFEXITED(status)){
printf("cp exit normal![%d]/n", errno) ;
printf("exit staus = [%X]/n", WEXITSTATUS(status)) ;
}else
printf("cp exit illegal![%d]/n", errno) ;
}
~
[tiantao@probe sys_test]$ cat sys_test.cpp
#include
#include
#include
#include
int main()
{
pid_t status ;
int errno = 0 ;
status = system("./rt") ;
printf("wifexited(status):%d/n",WIFEXITED(status));
printf("WEXITSTATUS(status):%d/n",WEXITSTATUS(status));
if (status == -1)
printf("system error!") ;
if (WIFEXITED(status)){
printf("cp exit normal![%d]/n", errno) ;
printf("exit staus = [%X]/n", WEXITSTATUS(status)) ;
}else
printf("cp exit illegal![%d]/n", errno) ;
}
==================================
编译后运行结果
==================================
Return 10.
wifexited(status):1
WEXITSTATUS(status):10
cp exit normal![0]
exit staus = [A]
==================================
可以看到:
WEXITSTATUS(status)可以得到调用程序的返回值。