Search code examples
clinuxprintfforkwait

How is "&" used to print the integer value of a process exit code?


I was looking at a didactical example, and I saw that my professor used this syntax to print the exit value of a child process:

wait(&value);
printf("last two bytes of value are %d - %d\n",(value>>8)&255,value&255); 

The "value" variable is defined as an int, and the wait() is used by the parent to wait the child process generated through a "fork()". The child can be terminated by a signal or it terminates by itself after a fixed amount of time. From what I've understood, since the variable "value" is an int it has 4 bytes, but the exit code of a "exit(int)" is written in just one of the four bytes. If the process is not terminated by an exit(), but instead from a signal, in another of those four bytes I recive the code of that signal. So I guess that the fact that I have "(value>>8)" is due to this use of the bytes, but what I don't understand is why I use the syntax with "&255" to print those values.


Solution

  • Ok, so there is some bit operations are going on:

    Imagine you have 32 bit integer:

    0101 0101 1011 0101 1101 1010 1111 1101

    1: (value>>8)&255 this will perform two operations: shift to the right 8 times, then "and" operation. After shift:

    0000 0000 0101 0101 1011 0101 1101 1010

    After "and" :

    0000 0000 0000 0000 0000 0000 1101 1010.

    This is the value of the first eight bits on the final result.

    1. value&255: this will perform "and" again, and you have:

    0000 0000 0000 0000 0000 0000 1111 1101

    This is the last 8 bits of the result.

    TL:DR

    value&255 Will zero out the first 24 bits of the 32 bit value.