0

I need to call through to a python script from C and be able to catch return values from it. it doesn't particularly matter what the values are, they may as well be an enum, but the values I got out of a test case confused me, and I wanted to get to the bottom of what I was seeing.

So, here is the C:

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

int main(void)
{
  int out = 0;

  out = system("python /1.py");
  printf("script 1 returned %d\n", out);

  return 0;
}

and here is /1.py :

import sys
sys.exit(1)

The output of these programs is this:

script 1 returned 256

some other values:

2       -> 512
800     -> 8192
8073784 -> 14336

Assuming that it is...reading in little rather than big endian, or something? how can I write a c function (or trick python in)to correctly returning and interpret the numbers?

2 Answers 2

2

From the Linux documentation on system():

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

From following the link on wait, we get the following:

WEXITSTATUS(status): returns the exit status of the child. ... This macro should only be employed if WIFEXITED returned true.

What this amounts to is that you can't use the return value of system() directly, but must use macros to manipulate them. And, since this is conforming to the C standard and not just the Linux implementation, you will need to use the same procedure for any operating environment that you are using.

Sign up to request clarification or add additional context in comments.

3 Comments

C99 §7.20.4.6.3: "If the argument is a null pointer, the system function returns nonzero only if a command processor is available. If the argument is not a null pointer, and the system function does return, it returns an implementation-defined value."
I'm not sure why the system() man page doesn't just say "you can access the return value by calling WEXISTSTATUS(system("command"));", but I'm sure there's a good reason. Thanks for clarifying :)
Because system() is part of the C standard and, as @Hasturkun pointed out to me, WEXITSTATUS is part of the POSIX standard. Although POSIX builds on C, not every C system implements POSIX. Concused yet?
1

The system() call return value is in the format specified by waitpid(). The termination status is not as defined for the sh utility. I can't recall but it works something like:

int exit_value, signal_num, dumped_core;

...

exit_value  = out >> 8;
signal_num  = out & 127;
dumped_core = out & 128;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.