Raven
Raven

Reputation: 1520

Why does the return from "system" not match the return of the script that was called?

I have a simple script

#!/usr/bin/bash
# exit5.bash
exit 5

And I call it with system in a c program

#include <stdlib.h>
#include <stdio.h>

int main()
{
    int ret = system("./exit5.bash");
    printf("%d\n", ret);
    return 0;
}

And I see 1280 printed to the screen, which is the same as 5 << 8

Why do I not see regular 5?

Upvotes: 5

Views: 73

Answers (1)

Daniel Pryden
Daniel Pryden

Reputation: 60957

The return value of system is a termination status, not an exit code.

See the return value section of man system:

In the last two cases, the return value is a "wait status" that can be examined using the macros described in waitpid(2). (i.e., WIFEXITED(), WEXITSTATUS(), and so on).

What you're looking for is returned by the WEXITSTATUS macro:

WEXITSTATUS(wstatus)

returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should be employed only if WIFEXITED returned true.

Upvotes: 5

Related Questions