Exit (system call)

Last updated

On many computer operating systems, a computer process terminates its execution by making an exit system call. More generally, an exit in a multithreading environment means that a thread of execution has stopped running. For resource management, the operating system reclaims resources (memory, files, etc.) that were used by the process. The process is said to be a dead process after it terminates.

Contents

How it works

Under Unix and Unix-like operating systems, a process is started when its parent process executes a fork system call. The parent process may then wait for the child process to terminate, or may continue execution (possibly forking off other child processes). When the child process terminates ("dies"), either normally by calling exit, or abnormally due to a fatal exception or signal (e.g., SIGTERM, SIGINT, SIGKILL), an exit status is returned to the operating system and a SIGCHLD signal is sent to the parent process. The exit status can then be retrieved by the parent process via the wait system call.

Most operating systems allow the terminating process to provide a specific exit status to the system, which is made available to the parent process. Typically this is an integer value, although some operating systems (e.g., Plan 9 from Bell Labs) allow a character string to be returned. Systems returning an integer value commonly use a zero value to indicate successful execution and non-zero values to indicate error conditions. Other systems (e.g., OpenVMS) use even-numbered values for success and odd values for errors. Still other systems (e.g., IBM z/OS and its predecessors) use ranges of integer values to indicate success, warning, and error completion results.

Clean up

The exit operation typically performs clean-up operations within the process space before returning control back to the operating system. Some systems and programming languages allow user subroutines to be registered so that they are invoked at program termination before the process actually terminates for good. As the final step of termination, a primitive system exit call is invoked, informing the operating system that the process has terminated and allows it to reclaim the resources used by the process.

It is sometimes possible to bypass the usual cleanup; C99 offers the _exit() function which terminates the current process without any extra program clean-up. This may be used, for example, in a fork-exec routine when the exec call fails to replace the child process; calling atexit routines would erroneously release resources belonging to the parent.

Orphans and zombies

Some operating systems handle a child process whose parent process has terminated in a special manner. Such an orphan process becomes a child of a special root process , which then waits for the child process to terminate. Likewise, a similar strategy is used to deal with a zombie process , which is a child process that has terminated but whose exit status is ignored by its parent process. Such a process becomes the child of a special parent process, which retrieves the child's exit status and allows the operating system to complete the termination of the dead process. Dealing with these special cases keeps the system process table in a consistent state.

Examples

The following programs terminate and return a success exit status to the system.

C:
#include<stdlib.h>intmain(void){exit(EXIT_SUCCESS);/* or return EXIT_SUCCESS */}
C++:
#include<cstdlib>intmain(){std::exit(EXIT_SUCCESS);// or return EXIT_SUCCESS}

COBOL:

IDENTIFICATIONDIVISION.PROGRAM-ID.SUCCESS-PROGRAM.PROCEDUREDIVISION.MAIN.MOVEZEROTORETURN-CODE.ENDPROGRAM.

Fortran:

program wikicall exit(0)end program wiki

Java:

publicclassSuccess{publicstaticvoidmain(String[]args){System.exit(0);}}

Pascal:

programwiki;beginExitCode:=0;exitend.

DR-DOS batch file: [1]

exit 0 

Perl:

#!/usr/bin/env perlexit;

PHP:

<?phpexit(0);

Python:

#!/usr/bin/env python3importsyssys.exit(0)

Unix shell:

exit0

DOS assembly:

; For MASM/TASM  .MODEL SMALL .STACK .CODE main PROC NEAR     MOV AH, 4Ch ; Service 4Ch - Terminate with Error Code     MOV AL, 0 ; Error code INT 21h ; Interrupt 21h - DOS General Interrupts main ENDP END main ; Starts at main

Some programmers may prepare everything for INT 21h at once:

    MOV AX, 4C00h ; replace the 00 with your error code in HEX

Linux 32-bit x86 Assembly:

; For NASM MOV AL, 1 ; Function 1: exit() MOV EBX, 0 ; Return code INT 80h ; # Passes control to interrupt vector # invokes system call—in this case system call# number 1 with argument 0
# For GAS  .text  .global _start  _start:     movl $1, %eax  # System call number 1: exit()     movl $0, %ebx  # Exits with exit status 0     int $0x80      # Passes control to interrupt vector # invokes system call—in this case system call# number 1 with argument 0

Linux 64-bit x86 64 Assembly: for FASM

formatELF64executable3entrystartsegmentreadableexecutablestart:; STUFF; exitingmoveax,60; sys_exit syscall number: 60xoredi,edi; set exit status to 0 (`xor edi, edi` is equal to `mov edi, 0` )syscall; call it

OS X 64-bit x86 64 Assembly: for NASM

global_mainsection.text_main:movrax,0x02000001; sys_exit syscall number: 1 (add 0x02000000 for OS X)xorrdi,rdi; set exit status to 0 (`xor rdi, rdi` is equal to `mov rdi, 0` )syscall; call exit()

Windows

On Windows, a program can terminate itself by calling ExitProcess or RtlExitUserProcess function.

See also

Related Research Articles

On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution but still has an entry in the process table: it is a process in the "Terminated state". This occurs for the child processes, where the entry is still needed to allow the parent process to read its child's exit status: once the exit status is read via the wait system call, the zombie's entry is removed from the process table and it is said to be "reaped". A child process always first becomes a zombie before being removed from the resource table. In most cases, under normal system operation zombies are immediately waited on by their parent and then reaped by the system – processes that stay zombies for a long time are generally an error and cause a resource leak, but the only resource they occupy is the process table entry – process ID.

<span class="mw-page-title-main">Netwide Assembler</span> Assembler for the Intel x86 architecture

The Netwide Assembler (NASM) is an assembler and disassembler for the Intel x86 architecture. It can be used to write 16-bit, 32-bit (IA-32) and 64-bit (x86-64) programs. It is considered one of the most popular assemblers for Linux and x86 chips.

<span class="mw-page-title-main">COMMAND.COM</span> Default command line for MS-DOS and Windows 9x

COMMAND.COM is the default command-line interpreter for MS-DOS, Windows 95, Windows 98 and Windows Me. In the case of DOS, it is the default user interface as well. It has an additional role as the usual first program run after boot, hence being responsible for setting up the system by running the AUTOEXEC.BAT configuration file, and being the ancestor of all processes.

<span class="mw-page-title-main">System call</span> Way for programs to access kernel services

In computing, a system call is the programmatic way in which a computer program requests a service from the operating system on which it is executed. This may include hardware-related services, creation and execution of new processes, and communication with integral kernel services such as process scheduling. System calls provide an essential interface between a process and the operating system.

x86 assembly language is the name for the family of assembly languages which provide some level of backward compatibility with CPUs back to the Intel 8008 microprocessor, which was launched in April 1972. It is used to produce object code for the x86 class of processors.

In computing, particularly in the context of the Unix operating system and its workalikes, fork is an operation whereby a process creates a copy of itself. It is an interface which is required for compliance with the POSIX and Single UNIX Specification standards. It is usually implemented as a C standard library wrapper to the fork, clone, or other system calls of the kernel. Fork is the primary method of process creation on Unix-like operating systems.

An environment variable is a user-definable value that can affect the way running processes will behave on a computer. Environment variables are part of the environment in which a process runs. For example, a running process can query the value of the TEMP environment variable to discover a suitable location to store temporary files, or the HOME or USERPROFILE variable to find the directory structure owned by the user running the process.

In computing, a parent process is a process that has created one or more child processes.

<span class="mw-page-title-main">Daemon (computing)</span> Computer program that runs as a background process

In multitasking computer operating systems, a daemon is a computer program that runs as a background process, rather than being under the direct control of an interactive user. Traditionally, the process names of a daemon end with the letter d, for clarification that the process is in fact a daemon, and for differentiation between a daemon and a normal computer program. For example, syslogd is a daemon that implements system logging facility, and sshd is a daemon that serves incoming SSH connections.

Signals are standardized messages sent to a running program to trigger specific behavior, such as quitting or error handling. They are a limited form of inter-process communication (IPC), typically used in Unix, Unix-like, and other POSIX-compliant operating systems.

The Program Segment Prefix (PSP) is a data structure used in DOS systems to store the state of a program. It resembles the Zero Page in the CP/M operating system. The PSP has the following structure:

In computer programming, an inline assembly is a feature of some compilers that allows low-level code written in assembly language to be embedded within a program, among code that otherwise has been compiled from a higher-level language such as C or Ada.

The exit status of a process in computer programming is a small number passed from a child process to a parent process when it has finished executing a specific procedure or delegated task. In DOS, this may be referred to as an errorlevel.

In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.

exit (command)

In computing, exit is a command used in many operating system command-line shells and scripting languages.

Fork–exec is a commonly used technique in Unix whereby an executing process spawns a new program.

In computing, exec is a functionality of an operating system that runs an executable file in the context of an already existing process, replacing the previous executable. This act is also referred to as an overlay. It is especially important in Unix-like systems, although it exists elsewhere. As no new process is created, the process identifier (PID) does not change, but the machine code, data, heap, and stack of the process are replaced by those of the new program.

crt0 is a set of execution startup routines linked into a C program that performs any initialization work required before calling the program's main function.

Spawn in computing refers to a function that loads and executes a new child process. The current process may wait for the child to terminate or may continue to execute concurrent computing. Creating a new subprocess requires enough memory in which both the child process and the current program can execute.

In computer operating systems, a process may wait for another process to complete its execution. In most systems, a parent process can create an independently executing child process. The parent process may then issue a wait system call, which suspends the execution of the parent process while the child executes. When the child process terminates, it returns an exit status to the operating system, which is then returned to the waiting parent process. The parent process then resumes execution.

References

  1. Paul, Matthias R. (1997-07-30) [1994-05-01]. "II.4. Undokumentierte Eigenschaften externer Kommandos". NWDOS-TIPs Tips & Tricks rund um Novell DOS 7, mit Blick auf undokumentierte Details, Bugs und Workarounds. MPDOSTIP. Release 157 (in German) (3 ed.). Archived from the original on 2016-11-05. Retrieved 2012-01-11. (NB. NWDOSTIP.TXT is a comprehensive work on Novell DOS 7 and OpenDOS 7.01, including the description of many undocumented features and internals. It is part of the author's yet larger MPDOSTIP.ZIP collection maintained up to 2001 and distributed on many sites at the time. The provided link points to a HTML-converted older version of the file.)