2012-09-12 50 views
0

我有一個用戶空間的代碼如下,故宮地址訪問

try 
{ 
some code 
... 
code that tries accessing forbidden address 
... 
some code 
} 
catch (all exceptions) 
{ 
some logs 
} 

將內核發送SIGSEGV信號給用戶進程對於此無效訪問,並會有怎樣的default行爲(不有任何信號處理程序安裝)。請問系統crash。試圖

+1

有一個在C.沒有的try/catch考慮使用C++代碼。 – dmp

+0

你用什麼方法「訪問禁止訪問的地址」? (爲什麼你甚至會這樣做)? 如果你是例如只需解引用一個NULL指針,你將在linux下得到一個sigsegv,但不是一個例外;你可以安裝一個信號處理程序,但這是平臺特定的 – codeling

+0

#nyarlathotep它不是故意的。 Mine是一個大型應用程序,其中有很多機會無效的內存訪問。就像遍歷鏈表一樣。 –

回答

1

代碼訪問禁止地址

你不能用C++ exceptions抓住這個。只有platform-dependent解決方案。

+0

謝謝。什麼是平臺依賴性? –

+0

@Sibi非跨平臺解決方案。 SEH例如http://msdn.microsoft.com/en-us/library/windows/desktop/ms680657%28v=vs.85%29.aspx – ForEveR

1

這種情況下不會產生異常。您需要設置信號處理程序。看看man signal如何做到這一點。

對於example

#include <stdio.h> 
#include <unistd.h> 
#include <signal.h> 
#include <string.h> 

static void hdl (int sig, siginfo_t *siginfo, void *context) 
{ 
    printf ("Sending PID: %ld, UID: %ld\n", 
      (long)siginfo->si_pid, (long)siginfo->si_uid); 
} 

int main (int argc, char *argv[]) 
{ 
    struct sigaction act; 

    memset (&act, '\0', sizeof(act)); 

    /* Use the sa_sigaction field because the handles has two additional parameters */ 
    act.sa_sigaction = &hdl; 

    /* The SA_SIGINFO flag tells sigaction() to use the sa_sigaction field, not sa_handler. */ 
    act.sa_flags = SA_SIGINFO; 

    if (sigaction(SIGTERM, &act, NULL) < 0) { 
     perror ("sigaction"); 
     return 1; 
    } 

    while (1) 
     sleep (10); 

    return 0; 
}