exit 終止程序
void exit(int status)
原型位於 stdlib.h, process.h
適用於 UNIX 系統,在 ANSI C 中有定義
eixt 終止調用進程, 在退出程序之前,關閉所有文件, 緩衝輸出內容將刷新定義,並調用所有已刷新的”出口函數“(由 atexit 定義)。
參數 status 被用來提供調用進程的出口狀態,一般來說, 0 表示正常出口, 非 0 值表示有錯誤發生。
此時 status 將置爲 下列值之一
EXIT_SUCCESS 正常終止程序
EXIT_FAILURE 非正常終止程序,並通知操作系統程序有錯
沒有返回值
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main()
{
int status;
printf(" Enter either 1 or 2/n");
status = getch();
/* Set DOS errorlevel, 不太懂哎 :( */
exit(status - '0');
/* Note: this line is never reached */
printf(" You'll never see this/n");
return 0;
}
atexit
功 能: 註冊終止函數(即main執行結束後調用的函數)
用 法: int atexit(atexit_t func);
注意:atexit()註冊的函數類型應爲不接受任何參數的void函數,
exit調用這些註冊函數的順序與它們 登記時候的順序相反。
與 ANSI C 兼容
#include<stdio.h>
#include<stdlib.h>
void exit_fn1(void)
{
printf("Exit function #1 called/n");
}
void exit_fn2(void)
{
printf("Exit function #2 called/n");
}
int main(void)
{
/* 註冊 exit_fn1 。Post exit function #1 */
atexit(exit_fn1);
/* 註冊 exit_fn2 。 Post exit function #2 */
atexit(exit_fn2);
return 0
;
}
return 0 ; 改成 exit(0) 時,輸出相同
return 0 ; 改成 _exit(0) 時, 什麼也不輸出, 因爲它不調用 出口函數
return 0
; 改成 abort()
時, 只輸出 Abnormal program termination