在日常的代码编程中 , 我们可以利用system  函数去调用一些我们自己想调用的命令 , 并获取他的返回值。

函数的原型如下:

  int system(const char *command);

上一段我自己写的代码:

 int main(void)
{
unsigned int val ; val = system("./a.out") ; val = WEXITSTATUS(val);
printf("vl = %d\n" , val) ; return ;
}

这段代码是直接调用了当前文件的a.out文件 , 并获取了他的返回值.

今天着重记一下这个返回值得注意事项,先看下man system  里面关于返回值的说明:

RETURN VALUE
The value returned is - 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(). 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(). If the value of command is NULL, system() returns nonzero if the shell is
available, and zero if not. system() does not affect the wait status of any other children.

返回值分为3类,

第一类 : 如果 system 分配子进程失败, 他会返回 -1;

第二类 :  如果 system  执行命令失败 , 返回127;

第三类 : 执行命令子进程命令成功 , 返回子进程所返回的值。

这个值是有问题的。这个值是一个16位的值。

低8位 , 存放的是如果你执行命令失败,所存放的值(127 == 7个1),

高8位, 存放的是你执行的那条命令所返回值。

就是这个8位的问题,让我着重讲一下:

通过上面的程序 , 我用了一个宏定义:

   val = WEXITSTATUS(val);  

这个直接左移动8位。

注意这个值只有八位 , 如果你的命令返回一个高于八位的值, 他就会出现我们无法避免的一个状况, 返回值有点不符我们的理想:

看一下我的 a.out  源代码:

 int main(void)
{
printf("hello kitty \n") ;
return ;
}

这里我的返回值是255, 看我执行一下system 那个程序 , 得出结果:

aplex@aplex:~/test/chen_test$ ./test
hello kitty
vl =

返回值正常 , 但是, 我再把返回值加1:

 int main(void)
{
printf("hello kitty \n") ;
return ;
}

再执行system 函数代码:

aplex@aplex:~/test/chen_test$ ./test
hello kitty
vl =

没错, 他只能返回0~255 的值, 超出8位就不能正常返回。

最新文章

  1. C#集合类型大盘点
  2. Yii2的深入学习--继承关系
  3. python限定类属性的类属性:__slots__
  4. css与js后边有?v=20160101
  5. hdu4914 Linear recursive sequence
  6. sql server 函数
  7. vs2013中国集
  8. 浏览器检测JS代码(兼容目前各大主流浏览器)
  9. filter过滤器的使用
  10. Git回退到服务器某个版本正确姿势
  11. 腾讯优图及知脸(ZKface)人脸比对接口测试(python)
  12. win10家庭版安装Docker for Windows
  13. Python Django 实用小案例2
  14. dubbo源码分析11——服务暴露2_doExport()方法分析
  15. 国际化之Android设备支持的语种
  16. CleanAop使用笔记
  17. selenium之测试卫星资料页面操作(元素遍历)
  18. 20165236 2017-2018-2 《Java程序设计》结对编程练习_四则运算
  19. 服务器推技术研究Comet
  20. Mac 下安装node.js(转载)

热门文章

  1. 分页探究--Filter+JSTL
  2. Linux下interface文件修改
  3. 9月26日JavaScript表单验证、正则表达
  4. SVN中Branch和Merge实践
  5. Servlet之Filter详解
  6. ERROR 1130 (HY000) Host ‘hostname’ is not allowed to connect to this MySQL server
  7. Lua之元表
  8. 序列化模块之 pickle 和 json
  9. 在VS2013中强制IIS Express应用程序池使用经典模式
  10. Win8 删除桌面右键中的显卡选项