Any benefit in using WEXITSTATUS macro in C over division by 256 on exit() status?

后端 未结 4 951
清酒与你
清酒与你 2020-12-03 05:48

I was doing an exercise for university where I had to return a value with exit, that value was actually a count of something. This could be above 255 (which exit() can\'t ha

4条回答
  •  我在风中等你
    2020-12-03 06:07

    And the real question in this topic, is the same thing to call this macro in my code as dividing by 256?

    It will probably always work in the cases where the child process terminates normally (i.e., by calling exit(), not by a segmentation fault, assertion failure, etc.).

    The status stored by waitpid() encodes both the reason that the child process was terminated and the exit code. The reason is stored in the least-significant byte (obtained by status & 0xff), and the exit code is stored in the next byte (masked by status & 0xff00 and extracted by WEXITSTATUS()). When the process terminates normally, the reason is 0 and so WEXITSTATUS is just equivalent to shifting by 8 (or dividing by 256). However, if the process is killed by a signal (such as SIGSEGV), there is no exit code, and you have to use WTERMSIG to extract the signal number from the reason byte.

提交回复
热议问题