網頁

2014年5月10日 星期六

setjmp and longjmp


  •  What is it ? (setjmp / longjmp)
    • This is basic function on unix/linux platform. With these two functions you can simulate the functionality like "try/catch" in C++ or Java programming language.
    • 簡單來說就是c語言版本的try/catch啦。

  • How to use it ? (example)
    • Description:
      • You can include setjmp.h in your code. After declare your own "jmp_buf"(in the local or global), you can call setjmp() and input this variable into this function in your code to save your current registers status like "program counters" into "jmp_buf".  This first argument of setjmp is "jmp_buf". After setjmp() returns, the "jump_buf" has the content of current registers status. And at this time, setjmp() returns "0".
      • And then you can call longjmp() later in your code.
      • After you call longjmp() in your code you will "goto or jump to" the location of setjmp() in your code. At this time, setjmp() returns what you inputs in your longjmp's second argument. 
      • NOTE: Do not use longjmp() before setjmp(), the behavior is undefined.
      • 簡單來說就是先呼叫 setjmp() 再呼叫longjmp(),詳情可以參考上面的example連結的範例。
      • 第一次呼叫setjmp()是用來把目前暫存器的值存入jmp_buf,這次setjmp是回傳0。
      • 之後呼叫longjmp()時就可以把此jmp_buf的值載入回暫存器。此時在longjmp()的第二個參數可以填入setjmp()的回傳值。
      • 呼叫完longjmp()後因為暫存器的值被載入回去,所以此時的program counter也會變回呼叫setjmp()時的PC值。
      • 這一次setjmp()就會返回你在longjmp()第二個輸入的參數值。
  •  How to implement it ?
    • The basic concept is like I mentioned above: 
      • Save all program register when call setjmp()
      • Load all program register when call longjmp()
    • For the more detail implementation description can refer here.
    • 原理其實很簡單,就是在呼叫setjmp()時會把一堆register的值存到jmp_buf裡面。而在longjmp()時再把jmp_buf裡面的值填回registers.可以參考這邊here.

沒有留言:

張貼留言