Briefly compare the three functions used in C to exit a process

  • 2020-04-02 03:18:46
  • OfStack

C language _exit() function: end process execution
The header file:


#include <unistd.h>

Definition function:


void _exit(int status);

Function description: _exit() is used to immediately terminate the execution of the current process, and return the parameter status to the parent process, and close the file not closed.


Note: _exit () does not handle the standard I/O buffer, use exit () to update the buffer.

C on_exit() function: sets the function to be called before the normal end of the program
The header file:


#include <stdlib.h>

Definition function:


int on_exit(void (* function) (int void*), void *arg);

On_exit () is used to set a function to be called before the normal end of the program. When the program calls exit() or returns from main, the function specified by the parameter function is called before it is actually terminated by exit().

Return value: returns 0 on success, -1 on failure, and the reason for the failure is in errno.

sample


#include <stdlib.h>
void my_exit(int status, void *arg)
{
  printf("before exit()!n");
  printf("exit (%d)n", status);
  printf("arg = %sn", (char*)arg);
}
main()
{
  char * str = "test";
  on_exit(my_exit, (void *)str);
  exit(1234);
}

Perform:


before exit()! exit (1234) arg = test

C atexit() function: sets the function to be called before the normal end of the program
The header file:


#include <stdlib.h>

Definition function:


int atexit (void (*function) (void));

Function description: atexit() is used to set a function to be called before the normal end of the program. When the program calls exit() or returns from main, the function specified by the parameter function is called first, and then the program is actually terminated by exit().

Return value: returns 0 on success, -1 on failure, and the reason for the failure is in errno.

sample


#include <stdlib.h>
void my_exit(void)
{
  printf("before exit () !n");
}
main()
{
  atexit (my_exit);
  exit(0);
}

Perform:


before exit()!


Related articles: