Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

system

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?

like image 975
DeepDeadpool Avatar asked May 24 '19 19:05

DeepDeadpool


People also ask

What is the difference between return codes and return values?

These values are referred to simply as return codes because they do not have the special property of SAS system return codes described above. Some functions -- notably OPEN, DOPEN, FOPEN, and MOPEN -- return values other than SAS system return codes.

What happens when you call the sysrc function?

Note: If you call the SYSRC function after executing a function that returns a SAS system return code, the value that the SYSRC function returns is the same as the value that the original function returned. In many cases, knowing the value of a SAS system return code enables you to determine whether an operation succeeded or failed.

What is the difference between system exit() and system return 0?

Note: The work of both return 0 and System.exit (0) is the same as the difference in the return type of the main () functions. 1. The main () function in C++ has a return type.

Can I return the text of an error message?

However, in some cases warning messages can be useful for informing users of special situations that may need to be corrected. You can use the SYSMSG function to return the text of the error message that was produced by the most recent SCL warning or error.


1 Answers

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.

like image 131
Daniel Pryden Avatar answered Nov 15 '22 05:11

Daniel Pryden