0

I am having a problem with wait () and exit () commands in process management in linux.

As far as I learn, the command wait (& val) will change the variable val of the parent program based on the exit state of the child process. That means when i run the command exit (val) the child process will terminate and give exit state 5 but the output of the code is 1281.

Can anyone explain to me why 1281 instead of 5 ?.Thanks for watching and hope you can answer.

 #include <stdio.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    int main()
    {
        int val = 5;
        if(fork())
            wait(&val);
        else
            exit(val);
        printf("%d\n", val);
        return val;
    }
  • The status passed to `exit()` is stored in the high-order 8-bits of a 16-bit value returned by `wait()`. Decimal 1281 corresponds to 0x0501. The exit status of `5` is present. What surprises me it the presence of the `1` in the low-order 8 bits. That normally encodes the signal that terminated the process, or is all zero if the process exited normally. – Jonathan Leffler Apr 08 '21 at 01:39
  • You should first check `WIFEXITED(val)` and then `WIFEXITSTATUS(val)` to get the actual return value of your child process. Read the [documentation](https://man7.org/linux/man-pages/man2/waitid.2.html) for more info. – paddy Apr 08 '21 at 01:41
  • It might help to use `%x` instead of `%d`, so you can see the raw value that comes from `wait`. The correct way to print your value [in decimal] is: `printf("%d\n",(val >> 8) & 0xFF);`. But, better to use the `W*` macros [to check for process being killed instead of just exiting]. – Craig Estey Apr 08 '21 at 01:45
  • See also [ExitCodes bigger than 255 — possible?](https://stackoverflow.com/q/179565/15168). – Jonathan Leffler Apr 08 '21 at 01:46

0 Answers0