Meaning of Exit Code 11 in C? - c

What's the general meaning of an exit code 11 in C? I've looked around and can not find a definitive answer so I thought I would ask here. It comes when i try to add an element to a vector.

You didn't find a definitive answer because there isn't one. It's up to the author of the program to decide what exit codes they wish to use. Standard C only says that exit(0) or exit(EXIT_SUCCESS) indicate that the program is successful, and that exit(EXIT_FAILURE) indicates an error of some kind. (Returning a value from main is equivalent to calling exit with that value.) Most common operating systems including Windows, Linux, OSX, etc. use 0 for success and values from 1 to 255 to indicate errors; still choosing between error codes is up to the application writer, the value 11 isn't anything special.
Under Linux and most other Unix variants, the signal number 11 indicates a segmentation fault, as remarked by Kerrek SB. A segmentation fault happens when a program makes some kind of invalid memory access, so it's a plausible consequence of accessing an array out of bounds, or an error in pointer arithmetic, or trying to access a null pointer, or other pointer-related errors. Signal 11 is not the same thing as exit code 11: when a program dies due to a signal, it's marked as having been killed by a signal, rather than having exited normally. Unix shells report signals by reporting an exit code which is the signal number plus 128, so 139 for a segmentation fault.

The other answers have missed a possible ambiguity in the phrase "exit code". I suspect what you meant by "exit code" is the status code retrieved with the wait family of syscalls, as in:
/* assume a child process has already been created */
int status;
wait(&status);
printf("exit code %d\n", status);
If you do something like that you may very will see "exit code 11" if the child process segfaults. If the child process actually called exit(11) you might see "exit code 2816" instead.
It would be better to call those things "wait code" or "wait status" instead of "exit code", to avoid confusion with the value passed to exit. A wait code contains several pieces of information packed together into a single integer. Normally, you should not look at the integer directly (like I did above in that printf). You should instead use the W* macros from <sys/wait.h> to analyze it.
Start with the WIF* macros to find out what kind of thing happened, then use that information to decide which other W* macros to use to get the details.
if(WIFEXITED(status)) {
/* The child process exited normally */
printf("Exit value %d\n", WEXITSTATUS(status));
} else if(WIFSIGNALED(status)) {
/* The child process was killed by a signal. Note the use of strsignal
to make the output human-readable. */
printf("Killed by %s\n", strsignal(WTERMSIG(status)));
} else {
/* ... you might want to handle "stopped" or "continued" events here */
}

There is no standard defined which exit codes an application has to set in certain situations. It is totally up to the programmer which exit codes represent which error or even success !
Sometimes programmers decide that any value different from zero signals an error, and sometimes this value equals the operating systems error codes.
On Windows exit code 11 might be used because of problems with a file. If you want the description of this error code (which is specific to Windows and not necessarily your application) run net helpmsg 11.

Related

How do I explain 'main()'?

I'm creating a presentation on how to program in C, and since I'm fairly new to C, I want to check whether my assumptions are correct, and what am I missing.
Every C program has to have an entry point for the OS to know where to begin execution. This is defined by the main() function. This function always has a return value, whether it be user defined or an implicit return 0;.
Since this function is returning something, we must define the type of the thing it returns.
This is where my understand starts to get hazy...
Why does the entry point needs to have a return value?
Why does it have to be an int?
What does the OS do with the address of int main() after the program executes?
What happens in that address when say a segfault or some other error halts the program without reaching a return statement?
Every program terminates with an exit code. This exit code is determined by the return of main().
Programs typically return 0 for success or 1 for failure, but you can choose to use exit codes for other purposes.
1 and 2 are because the language says so.
For 3: Most operating systems have some sort of process management, and a process exits by invoking a suitable operating system service to do so, which takes a status value as an argument. For example, both DOS and Linux have "exit" system calls which accept one numeric argument.
For 4: Following from the above, operating systems typically also allow processes to die in response to receiving a signal which is not ignored or handled. In a decent OS you should be able to distinguish whether a process has exited normally (and retrieve its exit status) or been killed because of a signal (and retrieve the signal number). For instance, in Linux the wait system call provides this service.
Exit statuses and signals provide a simple mechanism for processes to communicate with one another in a generic way without the need for a custom communications infrastructure. It would be significantly more tedious and cumbersome to use an OS which didn't have such facilities or something equivalent.

Return code for POSIX signals that cannot be handled

This is regarding the application that runs on POSIX (Linux) environment. Most signals (e.g. Ctrl+C - signal 2, SIGINT), and few others are handled. When that is done the exit() system call is called from the handler with a desirable exit code.
However, there are some signals like Signal 9 and Signal 15 can't be handled.
Unfortunately, the parent process (an external script) which launches the given application needs to know and clean up some stuff if the signal 9 or 15 was the reason for termination.
Is there a predefined exit code that can be received by parent process to know the above?
The script that launches the app is a bash_script. The application itself is in C.
The return status from wait() or waitpid() encodes the information you need.
The POSIX macros are:
WIFEXITED(status) returns true if the child exited via exit() or one of its relatives.
WEXITSTATUS(status) tells you what that exit status was (0..255).
WIFSIGNALED(status) returns true if the child exited because of a signal (any signal).
WTERMSIG(status) returns the signal number that killed the child.
The non-standard but common macro WCOREDUMP(status) tells you if the process dumped core. You can also tell whether status reflect that the process was stopped, or continued (and what the stop signal was).
Note that signal 15 is usually SIGTERM and SIGTERM can be trapped by an application. The signals that cannot be trapped are SIGKILL (9) and SIGSTOP (17 on Mac OS X; may not be the same everywhere).
The question then is if bash provides this info for a script.
The answer is yes, but only indirectly and not 100% unambiguously. The status value reported by bash will be 128 + <signum> for processes that terminate due to signal <signum>, but you can't distinguish between a process that exits with status 130, say, and a process that was interrupted by SIGINT, aka signal 2.
15 (SIGTERM) could be caught and handled by the application, if it so chose to do so, but perhaps it does not at the moment
9 (SIGKILL) obviously cannot be caught by any application.
However, typically the operating system sets the exit status in such a way that the signal which terminated the process can be identified. Normally only the lower 8 bits of the status parameter to the exit(3) function [and thus the _exit(2) system call] are copied into the status value returned by wait(2) to the parent process (the shell running the external script in your example). So, that leaves sizeof(int)-1 bytes of space in the status value for the OS to use to fill in other information about the terminated process. Typically the wait(2) manual page will describe the way to interpret the wait status and thus split appart any additional information about the process termination from the status the process passed to _exit(2), IFF the process exited.
Unfortunately whether or not this extra information is made available to a script depends on how the shell executing the script might handle it.
First check your shell's manual page for details on how to interpret $?.
If the shell makes the whole status int value available verbatim to the script (in the $? variable), then it will be possible to parse apart the value and determine how and why the program exited. Most shells don't seem to do this completely (and for various reasions, not the least of which might be standards compliance), but they do at least go far enough to make it possible to solve your query (and must, to be POSIX compatible).
Here for example I'm running the AT&T version of KSH on Mac OS X. My ksh(1) manual page says that the exit status is 0-255 if the program just run terminated normally (where the value is presumably what was passed to _exit(2)) and 256+signum if the process was terminated by a signal (numbered "signum"). I don't know about on Linux, but on OS X bash gives a different exit status than Ksh does (with bash using the 8'th bit to represent a signal and thus only allowing 0-127 as valid exit values). (There is discrepancy in the POSIX standard between wait(2)'s claim that 8 low-order bits of _exit(2) being available, and the shell's conversion of wait status to $? preserving only 7 bits. Go figure! Ksh's behaviour is in violation of POSIX, but it is safer, since a strictly compatible shell may not be able to distinguish between a process passing a value of 128-255 to _exit(2) and having been terminated by a signal.)
So, anyway, I start a cat process, then I send it a SIGQUIT from the terminal (by pressing ^) (I use SIGQUIT because there's no easy way to send SIGTERM from the terminal keyboard):
22:01 [2389] $ cat
^\Quit(coredump)
ksh: exit code: 259
(I have a shell EXIT trap defined to print $? if it is not zero, so you see it above too)
22:01 [2390] $ echo $?
259
(259 is an integer value representing the status returned by wait(2) to the shell)
22:02 [2391] $ bc
obase=16
259
103
^D22:03 [2392] $
(see that 259 has the hex value 0x0103, note that 0x0100 is 256 decimal)
22:03 [2392] $ signo SIGQUIT
#define SIGQUIT 3 /* quit */
(I have a shell alias called signo that searches headers to find the number representing a symbolic signal name. See here that 0x03 from the status value is the same number as SIGQUIT.)
Further exploration of the wait(2) system call, and the related macros from <sys/wait.h> will allow us to understand a bit more of what's going on.
In C the basic logic for decoding a wait status makes use of the macros from <sys/wait.h>:
if (!WIFEXITED(status)) {
if (WIFSIGNALED(status)) {
termsig = WTERMSIG(status);
} else if (WIFSTOPPED(status)) {
stopsig = WSTOPSIG(status);
}
} else {
exit_value = WEXITSTATUS(status));
}
I hope that helps!
It is not possible for a parent process to detect the SIGKILL or Signal 9 - given the SIGNAL occurs outside of the user space.
A suggestion would be to have your Parent Process detect whether your child process has gone away and deal with it accordingly.A Great example is seen in mysqld-safe etc.

What's the purpose of exit(0) ?

I understand that exit(1) indicated an error , for example :
if (something went wrong)
exit(EXIT_FAILURE);
But what's the purpose of using exit(EXIT_SUCCESS); ?
When handling with processes maybe ? e.g. for fork() ?
thanks
This gives the part of the system that invokes the program (usually the command shell) a way to check if the program terminated normally or not.
Edit - start -
By the way, it is possible to query the exit code of an interactive command as well through the use of the $? shell variable. For instance this failed ls command yields an exit code of value 2.
$ ls -3
ls: invalid option -- '3'
Try `ls --help' for more information.
$ echo $?
2
Edit - end -
Imagine a batch file (or shell script) that invokes a series of programs and depending on the outcome of each run may choose some action or the other. This action may consist of a simple message to the user, or the invocation of some other program or set of programs.
This is a way for a program to return a status of its run.
Also, note that zero denotes no problem, any non-zero value indicates a problem.
Programs will often use different non-zero values to pass more information back (other than just non-normal termination). So the non-zero exit value then serves as a more specific error code that can identify a particular problem. This of course depends on the meanings of the code being available (usually/hopefully in the documentation)
For instance, the ls man page has this bit of information at the bottom:
Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.
For Unix/Linux man pages, look for the section titled EXIT STATUS to get this information.
you can only exit your program from the main function by calling return. To exit the program from anywhere else, you can call exit(EXIT_SUCCESS). For example, when the user clicks an exit button.
It's a system call. There's always good information on system calls if you check the man pages:
http://linux.die.net/man/3/exit
On a Linux box, you can simply type man exit into a terminal and this information will come up.
There are two ways of 'normally' exiting a program: returning from main(), or calling exit(). Normally exit() is used, and thought of, for signalling a failure. However, if you are not in main(), you must still exit somehow. exit(0) is usually used to terminate the process when not in main().
main() is actually not a special function to the operating system, only to the runtime environment. The 'function' that actually gets loaded is normally defined as _start() (this is handled by the linker, and beyond the scope of this answer), written in assembly, which simply prepares the environment and calls main(). Upon return from main(), it also calls exit() with the return value from main().

Unused Return Status Codes in C

I want to return a unique status code to a waiting parent process from a child process through exit(), based on the execution of child's code. If execvp fails, then the exit() is used. I assume that if execvp is successful, the command executed will send its status code.
pid=fork();
if(pid==0)
{
if(execvp(cmdName,cmdArgs)==-1)
{
printf("Exec failed!\n");
exit(K); //K?
}
}
waitpid(pid,&status,0);
Suppose the command passed to execvp() is "ls", the man page says that it may return 0(success), 1 or 2(failure).
What safe unique value K can I use to indicate the return status of a child process, which won't clash with any value returned by the command executed by execvp()?
For obvious reasons, there cannot be such a value of K that will never clash with the return status of any other program.
Proof: Suppose there was such a K, and you make your program call itself...
There is no safe unique value as every program chooses its return values of which there are only a limited number.
You have to document your program and say what it returns and also provide some form of log to give more details.
I believe anything above 127 (or negative, if you use signed byte) is reserved for OS (on Unix) for reporting segfaults, parity errors and such (any exit due to signal handler and some other things besides). All other exit codes you can use.
Update: found a link for Linux: http://www.tldp.org/LDP/abs/html/exitcodes.html

Determine if a piece of code exits the program with MSVC

On a Gnu system, I can write a C macro like dies_ok() that will fork a new process, run a piece of code, after which it can write to a shared piece of memory that it didn't exit, then in the parent process I can determine if it exited or not. This is useful for tests:
dies_ok({int x = 0/0;}, "can't divide by zero");
lives_ok({int x = 3/7;}, "this is a perfectly fine statement");
dies_ok({abort();}, "abort kills the program");
Is there any way to accomplish this on MSVC where there isn't a fork function?
EDIT: Heres the implementation that works on linux with gcc: http://github.com/zorgnax/libtap/blob/master/tap.h
CreateProcess is like fork()/exec()
The BOOST library has shared memory support for msvc. You can also use the Windows atom table which is native to Windows-
see msdn for
http://msdn.microsoft.com/en-us/library/ms649053(VS.85).aspx
Q: I don't get why in unix you have to write a string to shared memory. You can simply call exit(n) from the child process where n is an index into a predefined char *p[] list of error codes or success codes. You can have an array of 255 values, excluding 0 for EXIT_SUCCESS. Or read the sysexits.h header file for another set of ideas. wait() or waitpid() will return the exit code, or determine if the process did not exit

Resources