c-正确的返回状态/值范围 [英] c - Proper range of return status / value

查看:37
本文介绍了c-正确的返回状态/值范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,在阅读有关linux编程的书时,我收到一条消息:

Recently, when reading a book about linux programming, I got a message that:

赋予_exit()的status参数定义了进程的终止状态,该进程的父级在调用wait()时可用.尽管定义为int,但实际上只有状态的低8位可用于父级.建议仅使用 0〜127 ,因为由于某种原因,128〜255在shell中可能会造成混淆.因此, -1 将成为2的补码中的 255 .

The status argument given to _exit() defines the termination status of the process, which is available to the parent of this process when it calls wait(). Although defined as an int, only the bottom 8 bits of status are actually made available to the parent. And only 0 ~ 127 is recommanded to use, because 128 ~ 255 could be confusing in shell due to some reason. Due to that -1 will become 255 in 2's complement.

上面是关于子进程的退出状态.

The above is about the exit status of a child process.

我的问题是:

  • 为什么父进程只获得子进程退出状态的8位?
  • 正常函数的返回值如何?仅使用 0〜127 是否合理?因为我确实使用 -1 作为返回值来表示错误,所以将来我应该更正此错误.
  • Why the parent process only get the 8 bits of the child process's exit status?
  • What about return value of normal functions? Does it reasonable or befinit to use only 0 ~ 127 ? Because I do use -1 as return value to indicate error sometimes, should I correct that in future.

更新-通过wait()/waitpid()获取状态:

我在本书(TLPI)中读了更多的chps,发现返回状态还有更多技巧.值得一提的wait()/waitpid(),在问这个问题之前,我应该阅读更多的chps.无论如何,我自己添加了一个答案来描述它,以防将来可能对某人有所帮助.

I read more chps in the book (TLPI), and found there are more trick in the return status & wait()/waitpid() that worth mention, I should have read more chps before ask the question. Anyhow, I have add an answer by myself to describe about it, in case it might help someone in future.

推荐答案

为什么父进程只获得子进程退出状态的8位?

Why the parent process only get the 8 bits of the child process's exit status?

因为POSIX 这么说.POSIX之所以这样说,是因为这就是原始Unix的工作方式,并且许多源自它的操作系统都可以继续工作.

Because POSIX says so. And POSIX says so because that's how original Unix worked, and many operating system derived from it and modeled after it continue to work.

正常函数的返回值如何?

What about return value of normal functions?

它们无关.退还任何合理的东西. -1 与任何其他值一样好,并且实际上是指示大量标准C和POSIX API中错误的标准方法.

They are unrelated. Return whatever is reasonable. -1 is as good as any other value, and is in fact a standard way to indicate an error in a huge lot of standard C and POSIX APIs.

这篇关于c-正确的返回状态/值范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆