如果我收到信号,我的程序的退出代码应该是什么?
What should my program's exit code be if I caught a signal?
我想我可能已经做错了一段时间了,因为我们刚刚切换到 systemd,它正在考虑我干净地杀死的进程未成功结束。
基本上我会听取 SIGHUP
、SIGINT
和 SIGTERM
,然后(通过将信号代码传回 main
)干净利落,例如return 128+SIGHUP
.
我原以为这是用来填充$?
,但现在我想我明白了shell负责给$?
这样一个值,然后仅当信号未处理时。因此,即使进程最终由于信号而退出,因为信号已被处理,$?
最终将成为 0
,并且信号与退出有任何关系的所有证据都将丢失。是吗?
当处理 SIGHUP
并干净退出时,我应该从 main
return EXIT_SUCCESS
吗?
Return 代码通常是您指定的。当您想要包含退出代码的信号时,您必须确保它们仍然保持唯一。
如果您不需要退出代码中的信号,那么似乎没有理由包含它们。
是returnEXIT_SUCCESS
还是EXIT_FAILURE
取决于you/your程序终止算作成功还是失败。
returning 128 + <signal number>
的约定由高级 Bash 脚本指南等 () 提倡,但仅适用于您的程序由于收到信号而失败。
如果您的程序收到信号,不会处理它,并因此终止,退出状态(如 wait
) will be similar but instead of bit 7 set will have a higher bit set to indicate WIFSIGNALED
as opposed to WIFEXITED
. If you are running in a shell, this is then translated by the shell 提供的那样给出一个退出状态 ($?
) 在 128-255 范围内(即设置了第 7 位),因此就 shell 脚本而言,程序 returning 128+n
与因未处理信号而终止的程序无法区分:
[...] When reporting the exit status with the special parameter '?', the shell shall report the full eight bits of exit status available. The exit status of a command that terminated because it received a signal shall be reported as greater than 128.
如果你的程序收到信号然后成功退出,这被认为是成功终止,所以你的程序应该return EXIT_SUCCESS
.
我想我可能已经做错了一段时间了,因为我们刚刚切换到 systemd,它正在考虑我干净地杀死的进程未成功结束。
基本上我会听取 SIGHUP
、SIGINT
和 SIGTERM
,然后(通过将信号代码传回 main
)干净利落,例如return 128+SIGHUP
.
我原以为这是用来填充$?
,但现在我想我明白了shell负责给$?
这样一个值,然后仅当信号未处理时。因此,即使进程最终由于信号而退出,因为信号已被处理,$?
最终将成为 0
,并且信号与退出有任何关系的所有证据都将丢失。是吗?
当处理 SIGHUP
并干净退出时,我应该从 main
return EXIT_SUCCESS
吗?
Return 代码通常是您指定的。当您想要包含退出代码的信号时,您必须确保它们仍然保持唯一。
如果您不需要退出代码中的信号,那么似乎没有理由包含它们。
是returnEXIT_SUCCESS
还是EXIT_FAILURE
取决于you/your程序终止算作成功还是失败。
returning 128 + <signal number>
的约定由高级 Bash 脚本指南等 () 提倡,但仅适用于您的程序由于收到信号而失败。
如果您的程序收到信号,不会处理它,并因此终止,退出状态(如 wait
) will be similar but instead of bit 7 set will have a higher bit set to indicate WIFSIGNALED
as opposed to WIFEXITED
. If you are running in a shell, this is then translated by the shell 提供的那样给出一个退出状态 ($?
) 在 128-255 范围内(即设置了第 7 位),因此就 shell 脚本而言,程序 returning 128+n
与因未处理信号而终止的程序无法区分:
[...] When reporting the exit status with the special parameter '?', the shell shall report the full eight bits of exit status available. The exit status of a command that terminated because it received a signal shall be reported as greater than 128.
如果你的程序收到信号然后成功退出,这被认为是成功终止,所以你的程序应该return EXIT_SUCCESS
.