免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6047 | 回复: 2
打印 上一主题 下一主题

wait()函数返回值问题讨论 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-04-25 21:47 |只看该作者 |倒序浏览
相信很多人看《unix环境高级编程》都看过下面的代码,

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <math.h>

void main(void)
{
pid_t child;
int status;

printf("This will demostrate how to get child status\n");
if((child=fork())==-1) {
  printf("Fork Error :%s\n",strerror(errno));
  exit(1);
}
else if(child==0) {
  int i;
  printf("I am the child:%ld\n",getpid());
  for(i=0;i<1000000;i++) sin(i);
  i=5;
  printf("I exit with %d\n",i);
  exit(i);
}
while(((child=wait(&status))==-1)&(errno==EINTR));

if(child==-1)
  printf("Wait Error:%s\n",strerror(errno));
else if(!status)
  printf("Child %ld terminated normally return status is zero\n",child);
else if(WIFEXITED(status))
  printf("Child %ld terminated normally return status is %d\n",child,WEXITSTATUS(status));
else if(WIFSIGNALED(status))
  printf("Child %ld terminated due to signal %d znot caught\n", child,WTERMSIG(status));  
}


wait函数后,要取得子进程返回值用函数WEXITSTATUS(status),以前一直没注意,刚刚发现当子进程返回值为负数时候有问题,查看该函数宏定义:
#define WEXITSTATUS(sv) ((sv >> 8 & 0xff)

本人觉得应该该为:
#define WEXITSTATUS(sv) ((sv >> 8 & ~0)

测试了几次结果都正确,大家帮忙看看是不是这样。

[ 本帖最后由 rock_jq 于 2008-4-25 21:54 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2008-04-25 22:33 |只看该作者
我这FC8下是这样的:
28 /* If WIFEXITED(STATUS), the low-order 8 bits of the status.  */
29 #define __WEXITSTATUS(status)   (((status) & 0xff00) >> 8)

论坛徽章:
0
3 [报告]
发表于 2008-06-12 16:19 |只看该作者
我试了试,你那个宏的重定义不能解决问题。

子进程正常退出(exit/_exit/return)时,父进程的wait(int *staloc)会把子进程退出状态保存在int *staloc的第二个字节上。
这里的关键是负数形式的子进程退出状态在计算机中是以补码表示的,经过WEXITSTATUS宏这么一操作,变成了正数。因为它只管简单地移位而已。

我有一个简单的办法,你们看好不好:

#define WEXITSTATUS(sv) (char(sv >> 8 & 0xFF))
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP