tehwalrus
tehwalrus

Reputation: 2659

c system() return from python script - confusing!

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?

Upvotes: 0

Views: 553

Answers (2)

Paulo Scardine
Paulo Scardine

Reputation: 77251

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;

Upvotes: 1

Kevin Lacquement
Kevin Lacquement

Reputation: 5117

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.

Upvotes: 2

Related Questions