Unix 程序中的退出状态约定
Exit status convention in Unix programs
考虑一个 Unix 命令 foo
逐行读取文件(或 stdin
),其中每一行都应遵循特定格式,例如/etc/passwd
格式。
如果有任何一行(但不是全部)不正确,终止状态应该是 EXIT_SUCCESS
还是 EXIT_FAILURE
?
我试过参考标准,
C11 Standard: 7.20.4.3 exit
函数
第 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.
我对上面的解释是 "implementation-defined" 意味着决定权留给实施者。这个解释正确吗?
你说得对,决定权在实施者手中。这取决于程序的使用方式。
例如,如果 foo
在遇到格式不正确的输入时因失败而终止,foo
的用户可以编写一个 shell 脚本来检查其退出状态并提醒她以及包含 stderr
内容的电子邮件。如果 foo
成功终止,则无需发送电子邮件。
C标准中的术语"implementation defined"表示平台实现,不是单个应用程序的程序员。
这句话的意思是,不同的平台可以对如何将成功或失败传输到环境(例如 shell)有不同的约定。实现也可以提供区分不同代码失败的方法,这取决于导致失败的原因。但是这样的代码可能无法在不同系统之间移植。
对于你作为程序员认为成功或失败的语义,你完全可以自由地做任何适合你的应用程序的事情。
考虑一个 Unix 命令 foo
逐行读取文件(或 stdin
),其中每一行都应遵循特定格式,例如/etc/passwd
格式。
如果有任何一行(但不是全部)不正确,终止状态应该是 EXIT_SUCCESS
还是 EXIT_FAILURE
?
我试过参考标准,
C11 Standard: 7.20.4.3 exit
函数
第 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 isEXIT_FAILURE
, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
我对上面的解释是 "implementation-defined" 意味着决定权留给实施者。这个解释正确吗?
你说得对,决定权在实施者手中。这取决于程序的使用方式。
例如,如果 foo
在遇到格式不正确的输入时因失败而终止,foo
的用户可以编写一个 shell 脚本来检查其退出状态并提醒她以及包含 stderr
内容的电子邮件。如果 foo
成功终止,则无需发送电子邮件。
C标准中的术语"implementation defined"表示平台实现,不是单个应用程序的程序员。
这句话的意思是,不同的平台可以对如何将成功或失败传输到环境(例如 shell)有不同的约定。实现也可以提供区分不同代码失败的方法,这取决于导致失败的原因。但是这样的代码可能无法在不同系统之间移植。
对于你作为程序员认为成功或失败的语义,你完全可以自由地做任何适合你的应用程序的事情。