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); DESCRIPTIONThe function _exit() terminates the calling process"immediately". Any open file descriptors belonging tothe process are closed; any children of the process areinherited by process 1, init, and the process"s parentis sent a SIGCHLD signal.The value status is returned to the parent process asthe process"s exit status, and can be collected usingone 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缓冲,遇到‘
"才会刷新,若直接调用exit()则会刷新,而_exit()则不会刷新)。
2.实例代码:#include <stdlib.h>void exit(int status);DESCRIPTIONThe exit() function causes normal process terminationand the value of status & 0377 is returned to the parent(see wait(2)).
这是man手册中对exit()函数的秒数,exit()函数导致子进程的正常退出,并且参数status&0377这个值将被返回给父进程。exit()应该是库函数。exit()函数其实是对_exit()函数的一种封装(库函数就是对系统调用的一种封装)。
3.return 不是系统调用,也不是库函数,而是一个关键字,表示调用堆栈的返回(过程活动记录),是函数的退出,而不是进程的退出。
return函数退出,将函数的信息返回给调用函数使用,与exit()和_exit()函数有本质区别。
4.abort()函数。 #include <stdlib.h>void abort(void);DESCRIPTIONThe abort() function causes abnormal program terminationunless the signal SIGABRT is caught and the signal han-dler does not return. If the abort() function causesprogram termination, all open streams are closed andflushed.If the SIGABRT signal is blocked or ignored, the abort()function will still override it.
abort()函数用于异常退出。返回一个错误代码。错误代码的缺省值是3。abort()函数导致程序非正常退出除非sigabrt信号被捕捉到,并且信号处理函数没有返回(即abort()函数给自己发送sigabrt信号),如果abort()函数导致程序终止,所有的打开的流将被关闭并且刷新。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!