gpt4 book ai didi

c - 关于STDIN、STDOUT、STDERR及返回值

转载 作者:行者123 更新时间:2023-11-30 18:30:38 27 4
gpt4 key购买 nike

我可以使用 < 重定向数据流>2>对于 STDIN , STDOUTSTDERR .

不知怎的,我把它们与返回值混淆了。

如果返回值为12怎么理解?

如果返回值为-1怎么理解?

break可以退出循环但继续执行下面的代码,return怎么样? ?一旦看到return ,它将终止 main()与返回代码,正确吗?

最佳答案

为了回答这个问题,我们来引用一下C99标准。如果您阅读7.20.4.3退出函数,您会发现以下语句:

5 Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

这里需要强调的是,C 标准没有指定任何特定的退出状态代码。虽然在上面的代码片段中您可以看到提到了,但它纯粹是 exit() API 的一部分。改写句子的其余部分,可以映射到任何其他实现定义的成功终止。同样,也不能保证 EXIT_SUCCESSEXIT_FAILURE 的定义不会映射到其他代码。特别是,它甚至可能不是一个整数。

此外,如果您查看7.20.4.6系统功能,您会注意到:

Returns 3 If the argument is a null pointer, the system function returns nonzero only if a command processor is available. If the argument is not a null pointer, and the system function does return, it returns an implementation-defined value.

这证实退出代码纯粹是实现定义的,并且您不能依赖任何特定行为。

<小时/>

现在,POSIX稍微扩展一下。如果您阅读 stdlib.h header ,您会发现:

EXIT_FAILURE

Unsuccessful termination for exit(); evaluates to a non-zero value.

EXIT_SUCCESS

Successful termination for exit(); evaluates to 0.

这已经限制了使用 0 的实现来成功退出。但是,它并没有真正定义哪个非零值用于失败。

如果您阅读 exit() 函数,您会发现:

The value of status may be 0, EXIT_SUCCESS, EXIT_FAILURE, or any other value, though only the least significant 8 bits (that is, status & 0377) shall be available to a waiting parent process.

它还通过保证 0…255 范围内的退出状态可供其他进程使用来扩展 C 定义。

因此,POSIX 将零定义为成功退出,EXIT_FAILURE(某些非零值)定义为不成功退出,并将剩余值留给程序使用。

但是,如果您正在解析来自其他进程的终止代码,则还应该查看 wait() 函数。它定义了额外的宏,用于处理非正常终止状态的返回状态,例如信号终止。

<小时/>

如果我们更进一步,我们可以发现FreeBSD引入了sysexits.h header 进一步定义退出代码。

The successful exit is always indicated by a status of 0, or EX_OK. Error numbers begin at EX__BASE to reduce the possibility of clashing with oth­ er exit statuses that random programs may already return. The meaning of the codes is approximately as follows:

EX_USAGE (64) The command was used incorrectly, e.g., with the wrong number of arguments, a bad flag, a bad syntax in a parameter, or whatever. […]

这意味着为 FreeBSD 编写的应用程序可以使用明确定义的退出代码 64+。

<小时/>

简单总结一下:

  1. C 标准仅定义用于返回成功不成功退出的 API。它没有定义如何使用、传递或获取该结果。
  2. POSIX 严格要求使用才能成功,并保证在正常进程终止的情况下,退出代码的 8 个最低有效位将可供其他进程使用(例如通过 等待())。
  3. FreeBSD 保留退出代码 64+ 以创建明确定义的错误条件退出代码。

这就是标准的发展程度。现在,实际上大多数程序使用来表示简单的成功,并使用非零代码来表示各种其他状态。使用退出代码传递特定信息的程序通常在联机帮助页中进行描述。

例如,如果您查看 GNU cmp:

An exit status of 0 means no differences were found, 1 means some differences were found, and 2 means trouble.

关于c - 关于STDIN、STDOUT、STDERR及返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29530447/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com