Exit (-1) or return (-1) Why did the shell get an exit code of 255?

Source: Internet
Author: User

Write a Hello World:

Filename:main.c#include <stdio.h>int Main (void) {printf ("Hello wolrd!\n");   Return (-1); }

Compile execution: gcc main.c &&./a.out

Now let's see what is the return value of the previous execution in the current shell, which is "1"?

[Email protected]:~/Desktop $ gcc main.c &&./a.outhello [email protected]:~/desktop $ echo $?255


Ah, the result why "255"? Call a program, program exit-1, get the result is not "1"?

The following references are from: http://www.laruence.com/2012/02/01/2503.html

This is simply because the exit or return in the main function only uses the value between 0~255. -The unsigned value of 1 is 255.

What's so complicated about that?

We know that in the shell, running a command, a program, is to fork a child process (and then exec) to execute, and this program's exit code, by the shell (parent process), through wait to collect and then report to us.

    1. pid_t wait (int *statloc);

For wait, for historical reasons, he will return a 16bit interge via Statloc (now also available in 32-bit notation, but will be compatible with existing designs). In this 16bits interge, the high 8 bits are the value of the program exit (exit, or return), and the low eight bits indicate the signal that caused the program to exit (one of them indicates whether a core file was generated), and if the program exits normally, the low eight bits are 0[1] .

So, if we return 1, and because we exit normally, the child process that the shell collects through wait exits the status:

    1. 11111111 00000000

And the high eight-bit as unsigned, is 255.

In addition, many of the built-in shell commands in Linux will adhere to an exit status code that corresponds to the meaning of the value [2]:



Exit (-1) or return (-1) Why did the shell get an exit code of 255?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.