Sunday 2 June 2013

setjmp and longjmp

In short, functions setjmp and longjmp just work like label&goto instruction, except that the combination of label&goto only can be used within the same function which means you cannot goto the label outside the function. But the combination of setjmp and longjmp can be used anywhere in the whole program.

For example, we use label&goto to implement a jump function:

main()
{
     int a=1, b=2, c=0;
label:
     c=a+b;
     goto label;
     
}

Now we implement the same function using setjmp and longjmp:

typedef long jmp_buf[16];

main()
{
     int a=1, b=2, c=0;
     jmp_buff environment;
     setjmp (evironment);
     c=a+b;
     longjmp(evironment, 1);
}

So from above, we can see the jump buffer environment contains all the context around the setjmp function, so it works like label. And then the longjmp function will jump to the position where environment assigned.

The prototype of setjmp and longjmp:

int setjmp(jmp_buff env);
void longjmp(jmp_buff env, int val);

So function longjmp never return any value, because it will just jump the execution flow to setjmp position, but once jump to setjmp position, the setjmp function will return the value assigned by val which is the second parameter of longjmp function.

The first time setjmp function is called, it will always return 0. But after longjmp is executed, and jump to setjmp function, setjmp will never return 0. (Even if you set val to 0, setjmp will also return 1).

To make every thing more clearer, let's see an example from reference [1]:

  1. #include<stdio.h>  
  2. #include<setjmp.h>  
  3. jmp_buf ebuf;  
  4. int f2();  
  5. int main()  
  6.  {  
  7.        int i;  
  8.        printf("1");  
  9.        i=setjmp(ebuf);  
  10.        if(i==0)  
  11.        {  
  12.            f2();  
  13.            printf("This will not beprinted.");  
  14.        }  
  15.        printf("%d",i);  
  16.        return 0;  
  17. }  
  18. int f2()  
  19. {  
  20.        printf("2");  
  21.        longjmp(ebuf,3);  
  22. }  

The output of this example will print "1 2 3"


Reference: 
[1] http://blog.csdn.net/sunlylorn/article/details/7178575 

No comments:

Post a Comment

Difference between "docker stop" and "docker kill"

 To stop a running container, you can use either "docker stop" or "docker kill" command to do so. Although it seems doin...