A summary of some common functions under linux

  • 2020-05-12 06:37:29
  • OfStack

1. exit () function

exit(int n) is simply exiting the program,

Because the default standard program entry is int main(int argc, char** argv), the return value is int.

1. Run a program under shell, then use the command echo $? You get the return value of the program, which is the exit value. In main(), you can use return n, or you can use exit(n) directly. The default custom correct exit for unix is to return 0, and error returns non-0.

Important: individual processes are returned to the operating system. If it is multiple processes, it is returned to the parent process.

Functions such as waitpid() are called inside the parent process to get the exit status of the child process for different processing

The return value cannot exceed 255.

It's defined in stdlib.h


#define    EXIT_SUCCESS    0 
#define    EXIT_FAILURE    1 

There are two types of termination for C programs: normal and abnormal.

Normal terminations are divided into: return, exit, _exit, _Exit, pthreade_exit

Exception: abort, SIGNAL, thread response cancelled

It mainly refers to the first four types of normal termination, namely exit series functions.


#include <stdlib.h>
void exit(int status);
void _Exit(int status);
#include <unistd.h>
void _exit(int status);

The difference between the above three functions is:

exit()(or return 0) calls the termination handler and the standard I/O cleanup (such as fclose) for user space, while _exit and _Exit are not called and are taken over directly by the kernel for cleanup.


#include<stdlib.h>
int atexit(void (*function)(void))

Return value: returns 0 on success, non-zero on failure.

ISO C states that a process can register up to 32 terminating functions, which are automatically called by exit in the reverse order of registration. If the same function is registered more than once, it will be called more than once.


#include<stdlib.h>
#include<unistd.h>
static void my_exit1()
{
printf("first exit handlern\n");
}

static void my_exit2()
{
 printf("second exit handlern\n");
}

int main()
{
 if (atexit(my_exit2) != 0)
printf("can't register my_exit2n\n");
 if (atexit(my_exit1) != 0)
printf("can't register my_exit1n\n");
 if (atexit(my_exit1) != 0)
printf("can't register my_exit1n\n");

 printf("main is donen\n");
 return 0;
}

addia@addia-Lenovo-B470:~$ ./test
main is donen
first exit handlern
first exit handlern
second exit handlern

Related articles: