Exit system () not as expected

The system () function seems to return 128 times the exit code that I get from the called process.

On the man page:

RETURN VALUE The return value is -1 on error (for example, fork (2) failed), and the return status of the other command is wise.

Here is what I have.

$ ls tinker.c tinker.c $ echo $? 0 $ ls notexisting ls: cannot access notexisting: No such file or directory $ echo $? 2 $ cat tinker.c #include <stdio.h> #include <stdlib.h> int main(void) { printf("%d\n", system("ls tinker.c")); printf("%d\n", system("ls notexisting")); return 0; } $ gcc tinker.c -o tinker $ ./tinker tinker.c 0 ls: cannot access notexisting: No such file or directory 512 

The first call indicates that I am not getting crashes, but the return codes do not look the way I read from the man page. What am I doing wrong?

+4
source share
3 answers

From the POSIX system(3) :

If the command is not a null pointer, system () returns the completion status of the command interpreter in the format specified by waitpid () .

To get the return code, you need to use the WEXITSTATUS macro.

+2
source

Your link to the system manual page skips the relevant part:

... This last return status is in the format specified in wait (2). Thus, the command exit code will be WEXITSTATUS (status).

You need to change the return value to 8 (at least on Linux) to get the command exit code.

A portable approach is to simply use the macro itself.

+2
source

0 and 512 are the completion status of the command .

If the command succeeds, it returns 0, otherwise a nonzero value is returned. And this nonzero value is different in different OSs. In my mac os, the return value of the second system command is 256.

You can also get the answer to this `ls` exit status .

0
source

Source: https://habr.com/ru/post/1446781/


All Articles