C++ 中exit(),_exit(),return,abort()函数的区别

2020-01-18 19:18:28丽君

exit()函数与_exit()函数及return关键字的区别:

  exit()和_exit()函数都可以用于结束进程,不过_exit()调用之后会立即进入内核,而exit()函数会先执行一些清理之后才会进入内核,比如调用各种终止处理程序,关闭所有I/O流等,我建议直接在Linux的终端中查看man手册,手册的内容是最官方的,而且不会有错,手册的英文是为全世界的程序员做的,所以手册的英语不会难。

1. 实例代码:


#include <unistd.h>

    void _exit(int status);

    #include <stdlib.h>

    void _Exit(int status);

 DESCRIPTION
    The function _exit() terminates the calling process
    "immediately". Any open file descriptors belonging to
    the process are closed; any children of the process are
    inherited by process 1, init, and the process's parent
    is sent a SIGCHLD signal.

    The value status is returned to the parent process as
    the process's exit status, and can be collected using
    one of the wait() family of calls.

  这是手册对_exit()函数的描述,意思是_exit()函数终止调用的进程,进程所有的文件描述符(在linux中一切皆文件)都被关闭, 这个进程的所有子进程将被init(最初的进程,所有的进程都是来自init进程,所有的进程都由其父进程创建,即init进程是所有进程的祖先!)进程领养,并且这个终止的进程将向它的父进程发送一个sigchld信号。_exit()的参数status被返回给这个终止进程的父进程来作为这个终止进程的退出状态,这个退出状态值能被wait()函数族的调用收集(就是通过wait()函数来获得子进程的退出状态,之后wait()函数将会释放子进程的地址空间,否则会出现zoom进程)。

  _exit()函数是系统调用。会清理内存和包括pcb(内核描述进程的主要数据结构)在内的数据结构,但是不会刷新流,而exit()函数会刷新流。比如exit()函数会将I/O缓冲中的数据写出或读入(printf()就是I/O缓冲,遇到‘n'才会刷新,若直接调用exit()则会刷新,而_exit()则不会刷新)。

  2.实例代码:


#include <stdlib.h>

    void exit(int status);

DESCRIPTION
    The exit() function causes normal process termination
    and the value of status & 0377 is returned to the parent
    (see wait(2)).

这是man手册中对exit()函数的秒数,exit()函数导致子进程的正常退出,并且参数status&0377这个值将被返回给父进程。exit()应该是库函数。exit()函数其实是对_exit()函数的一种封装(库函数就是对系统调用的一种封装)。

 3.return 不是系统调用,也不是库函数,而是一个关键字,表示调用堆栈的返回(过程活动记录),是函数的退出,而不是进程的退出。