C 庫 - atexit() 函式



C 的stdlibatexit() 函式會在程式正常終止時呼叫指定的函式“func”。我們可以在任何地方註冊終止函式,但它將在程式終止時被呼叫。

當透過對 atexit() 函式的不同調用指定多個函式時,它們將按照棧的順序執行。

此函式通常用於執行清理任務,例如在程式退出之前儲存狀態、釋放資源或顯示訊息。

語法

以下是 atexit() 函式的 C 庫語法:

int atatexit(void (*func)(void))

引數

此函式接受一個引數:

  • func - 它表示指向在程式正常終止時要呼叫的函式的指標。

返回值

此函式返回以下值:

  • - 如果函式註冊成功。
  • 非零 - 如果函式註冊失敗。

示例 1

在此示例中,我們建立一個基本的 C 程式來演示 atexit() 函式的使用。

#include <stdio.h>
#include <stdlib.h>

void tutorialspoint(void) {
   printf("tutorialspoint.com India\n");
}

int main() {
   if (atexit(tutorialspoint) != 0) {
      fprintf(stderr, "Failed to register the tutorialspoint function with atexit\n");
      return EXIT_FAILURE;
   }
   
   printf("This will be printed before the program exits.\n");
   return EXIT_SUCCESS;
}

輸出

以下是輸出:

This will be printed before the program exits.
tutorialspoint.com India

示例 2

讓我們建立一個另一個 C 程式,其中 atexit() 函式被多次呼叫。因此,所有指定的函式都按棧的順序執行。

#include <stdio.h>
#include <stdlib.h>

// first function
void first() {
   printf("Exit 1st \n");
}
// second function
void second() {
   printf("Exit 2nd \n");
}
// third function
void third() {
   printf("Exit 3rd \n");
}
// main function
int main() {
   int value1, value2, value3;
   value1 = atexit(first);
   value2 = atexit(second);
   value3 = atexit(third);
   if ((value1 != 0) || (value2 != 0) || (value3 != 0)) {
      printf("registration Failed for atexit() function. \n");
	  exit(1);
   }
   // it will execute at the first
   printf("Registration successful \n");
   return 0;
}

輸出

以下是輸出:

Registration successful
Exit 3rd
Exit 2nd
Exit 1st

示例 3

在這裡,我們建立了一個 C 程式,它執行兩個數字的加法和減法,並使用 atexit() 以棧的方式顯示這些函式的結果。

#include <stdio.h>
#include <stdlib.h>

// first function
void add() {
   int a=10;
   int b=5;
   int res = a+b;
   printf("addition of two number is: %d\n", res);
}
// second function
void sub() {
   int a=10;
   int b=5;
   int res = a-b;
   printf("subtraction of two number is: %d\n", res);
}
// main function
int main() {
   int value1, value2;
   value1 = atexit(add);
   value2 = atexit(sub);
   if ((value1 != 0) || (value2 != 0)) {
      printf("registration Failed for atexit() function. \n");
      exit(1);
   }
   // it will execute at the first
   printf("calculation successful \n");
   return 0;
}

輸出

以下是輸出:

calculation successful
subtraction of two number is: 5
addition of two number is: 15
廣告

© . All rights reserved.