簡體   English   中英

在線程庫的C函數中添加信號處理程序

[英]Adding signal handler to a function in C for a thread library

我正在編寫一個基本的用戶級線程庫。 用於創建線程的函數原型為thr_create (start_func_pointer,arg) { make_context(context_1,start_func) }

start_func將由用戶定義,並且可以根據用戶/程序進行更改

創建線程后一次,如果我開始使用swapcontext(context_1,context_2)執行它

函數start_func將開始運行。 現在,如果有信號進入,我需要處理它。 不幸的是,我只有start_func的句柄,所以我無法在start_func內真正定義信號動作

有沒有一種方法可以在start_function中添加信號處理結構並將其指向我的代碼。 像這樣的東西

thr_create (start_func_pointer,arg) { start_func.add_signal_hanlding_Structure = my_signal_handler(); make_context(context_1,start_func) } thr_create (start_func_pointer,arg) { start_func.add_signal_hanlding_Structure = my_signal_handler(); make_context(context_1,start_func) }有人知道posix是怎么做的嗎?

如果您正在談論從實際的操作系統中捕獲實際信號,那么我相信您將必須在整個應用程序中進行操作,然后將信號向下傳遞到每個線程中(稍后再介紹)。 問題是,如果您的兩個(或多個)線程試圖使用使用SIGALRM alarm會變得很復雜-當真正的信號發生時,您可以捕獲它,但是將信號傳遞給誰(一個或全部)的線程?)。

如果您正在談論使用庫在程序中的線程之間發送和捕獲信號,那么向線程發送信號將導致該信號被標記為可以運行,即使它之前正在等待其他東西,然后再發出任何信號處理功能將從您的線程恢復代碼中調用。 如果我記得您以前的問題,則有一個名為thread_yield的函數被調用以允許下一個線程運行。 如果是這種情況,那么thread_yield需要檢查待處理信號列表並執行其操作,然后再返回到調用thread_yield位置(除非其中一個信號處理程序涉及殺死當前線程,在這種情況下,您必須執行其他操作) 。

至於如何實現信號處理程序的注冊,在POSIX中是由主要功能(直接或間接)進行的系統調用完成的。 因此,您可以:

static int foo_flag = 0;

static void foo_handle(int sig) {
     foo_flag = 1;
}

int start_func(void * arg) {
    thread_sig_register(SIGFOO, foo_handle);

    thread_pause();
    // this is a function that you could write that would cause the current thread
    // to mark itself as not ready to run and then call thread_yield, so that
    // thread_pause() will return only after something else (a signal) causes the
    // thread to become ready to run again.


    if (foo_flag) {
        printf("I got SIGFOO\n");
    } else {
        printf("I don't know what woke me up\n");
    }
    return 0;
}

現在,您可以從另一個線程向該線程發送一個SIGFOO(這只是我為演示目的制作的信號)。

每個線程控制塊(或您要調用的任何塊)都必須具有信號處理程序表(或列表,或其他內容)和未決的信號列表,或將信號標記為未決的方法。 將檢查待處理信號(可能以某種優先級順序),並在返回該線程正常代碼之前為每個待處理信號執行處理程序操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM