C 庫 - longjmp() 函式



C 庫的 longjmp() 函式恢復了在程式同一呼叫中由最近一次對 setjmp() 宏的呼叫(使用相應的 jmp_buf 引數)儲存的環境。

假設在許多其他函式內的巢狀函式中發生錯誤,並且錯誤處理為頂級函式建立了一種意義。對於所有中間任務來說,正常返回並評估返回值或全域性錯誤變數以確定進一步處理的有效性或無效性將更加困難。因此,longjmp() 提供了一個非本地跳轉回程式中的特定點,並且通常函式會呼叫更高一級的棧。

語法

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

void longjmp(jmp_buf environment, int value)

引數

此函式接受以下引數:

  • environment - 這是一個 jmp_buf 型別的物件,包含在 setjmp 呼叫點恢復環境的資訊。
  • value - 這是 setjmp 表示式計算結果的值。

返回值

此函式不返回任何值。

示例 1

以下是一個基本的 C 程式,用於演示 longjmp() 函式。

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
int main() {
    int val;
    jmp_buf env_buffer;

    /* Save calling environment for longjmp */
    val = setjmp(env_buffer);

    if (val != 0) {
        printf("Returned from a longjmp() with value = %d\n", val);
        exit(0);
    }
    printf("Jump function call\n");
    jmpfunction(env_buffer);

    return 0;
}

void jmpfunction(jmp_buf env_buf) {
    longjmp(env_buf, 50);
}   

輸出

執行程式碼後,我們得到以下結果:

Jump function call
Returned from a longjmp() with value = 50

示例 2

下面的程式描述了 longjmp 函式,它使用 setjmp.h 標頭檔案設定跳轉點並在 jump_buffer 中儲存當前執行上下文。然後透過呼叫自定義函式 error_handler 觸發錯誤。最後,程式流程在跳轉後返回到 main() 並允許進行錯誤處理。

#include <stdio.h>
#include <setjmp.h>

jmp_buf jump_buffer;

void error_handler() {
   printf("The error is detected! Jumping back to main...\n");
   longjmp(jump_buffer, 1);
}

int main() {
   if (setjmp(jump_buffer) == 0) {
   
       // Normal execution
       printf("Welcome to the program!\n");
       printf("Let's simulate an error...\n");
       error_handler();
   } 
   else {
   
       // Error handling
       printf("Back in main after longjmp().\n");
       printf("Error handling success.\n");
   }
    return 0;
}

輸出

執行上述程式碼後,我們得到以下結果:

Welcome to the program!
Let's simulate an error...
The error is detected! Jumping back to main...
Back in main after longjmp().
Error handling success.
廣告

© . All rights reserved.