- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - exit() 函式
C 的stdlib 庫exit() 函式允許我們立即終止或退出呼叫程序。exit() 函式關閉屬於程序的所有開啟的檔案描述符,並且程序的任何子程序都將由程序 1(init)繼承,並且程序父程序將收到 SIGCHLD 訊號。
“SIGCHLD”訊號用於管理子程序,允許父程序處理其終止並收集退出狀態。
語法
以下是exit() 函式的 C 庫語法 -
void exit(int status)
引數
此函式接受一個引數 -
status - 它表示返回給父程序的狀態值或退出程式碼。
- 0 或 EXIT_SUCCESS:0 或 EXIT_SUCCESS 表示程式已成功執行,未遇到任何錯誤。
- 1 或 EXIT_FAILURE:1 或 EXIT_FAILURE 表示程式遇到錯誤,無法成功執行。
返回值
此函式不返回值。
示例 1:帶有狀態“EXIT_FAILURE”的 exit()
讓我們建立一個基本的 c 程式來演示 exit() 函式的使用。
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
printf("Opening the tutorialspoint.txt\n");
// open the file in read mode
fp = fopen("tutorialspoint.txt", "r");
if (fp == NULL) {
printf("Error opening file\n");
// Terminate the program with an error code
exit(EXIT_FAILURE);
}
fclose(fp);
// Terminate the program successfully
exit(EXIT_SUCCESS);
}
輸出
以下是輸出 -
Open the tutorialspoint.txt Error opening file
示例 2
在此示例中,我們使用exit() 函式在 'i' 達到 5 時立即終止程序。
#include <stdio.h>
#include <stdlib.h>
int main(){
// print number from 0 to 5
int i;
for(i=0;i<=7;i++){
// if i is equals to 5 then terminates
if(i==5){
exit(0);
}
else{
printf("%d\n",i);
}
}
return 0;
}
輸出
以下是輸出 -
0 1 2 3 4
示例 3
這是一個獲取使用者詳細資訊的另一個程式。如果使用者詳細資訊與 if 條件匹配,則 'exit(EXIT_SUCCESS)' 將起作用。否則 'exit(EXIT_FAILURE)'。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
const char *username = "tutorialspoint";
const char *password = "tp1234";
// Check the credentials
if (strcmp(username, "tutorialspoint") == 0 && strcmp(password, "tp1234") == 0){
printf("Login successful!\n");
// if user details match exit
exit(EXIT_SUCCESS);
} else {
fprintf(stderr, "Invalid credentials!\n");
// if user details not match exit
exit(EXIT_FAILURE);
}
return 0;
}
輸出
以下是輸出 -
Login successful!
廣告