If yes, on which operating system, shell or whatever?
Consider the following Java program (I’m using Java just as an example; any language would be good for this question, which is more about operation systems):
public class ExitCode { public static void main(String args[]) { System.exit(Integer.parseInt(args[0])); } }
Running it on Linux and bash, it returns always values less equal 255, e.g. (echo $? prints the exit code of the previous executed command)
> java ExitCode 2; echo $? 2 > java ExitCode 128; echo $? 128 > java ExitCode 255; echo $? 255 > java ExitCode 256; echo $? 0 > java ExitCode 65536; echo $? 0
EDITED: most of the answers below fully explain what happens on UNIX variants. I’m still wondering about other OSes.
Using
wait()orwaitpid()It is not possible on Unix and derivatives using POSIX functions like
wait()andwaitpid(). The exit status information returned consists of two 8-bit fields, one containing the exit status, and the other containing information about the cause of death (0 implying orderly exit under program control, other values indicating that a signal killed it, and indicating whether a core was dumped).Using
sigaction()withSA_SIGINFOIf you work hard, and read the POSIX specification of
sigaction()and<signal.h>and Signal Actions, you will find that you can get hold of the 32-bit value passed toexit()by a child process. However, it is not completely straight-forward.When run (program
sigexit73compiled fromsigexit73.c), this produces output like:With the one millisecond call to
nanosleep()removed, the output is apt to look like:Note that there are only three lines starting
Signalhere, and also only three lines endingwaited; some of the signals and exit statuses are lost. This is likely to be because of timing issues between theSIGCHLDsignals being set to the parent process.However, the key point is that 4 bytes of data can be transmitted in the
exit()status when the code usessigaction(),SIGCHLD,SA_SIGINFOto track the status.Just for the record, the testing was performed on a MacBook Pro running macOS Mojave 10.14.6, using GCC 9.2.0 and XCode 11.3.1. The code is also available in my SOQ (Stack Overflow Questions) repository on GitHub as file
sigexit73.cin the src/so-1843-7779 sub-directory.