LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   script exit code to system() c function (https://www.linuxquestions.org/questions/programming-9/script-exit-code-to-system-c-function-737523/)

nemobluesix 07-03-2009 12:20 PM

script exit code to system() c function
 
Hi guys,

Consider the following code:
Code:

...
int ret=0;
ret=system("exit 1");
...

ret should become 1 but instead it gets 256.

This is a cgi script if it matters...

What am I missing?
Thx

aspire1 07-03-2009 01:35 PM

A quick google turned up as far as I can tell that you should run the result through WEXITSTATUS

Code:

#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>

int main()
{
        int ret = 0;
        ret = WEXITSTATUS(system("exit 1"));
        printf("%d\n", ret);

}


nemobluesix 07-05-2009 06:28 AM

thanks aspire1!
It works, can's say "as expected", but it works :).

thanks again

bigearsbilly 07-05-2009 08:12 AM

look at man waitpid maybe.

the lower 8 bits from a system is a bitmask.
these signify how the process exited e.g. a signal.
the actual return code you need to right shift by 8.

this may be of interest to you,
observe, simplified from aspire:
Code:

#include <sys/wait.h>

main(int argc, char ** argv)
{
    WEXITSTATUS(256);
}


if i put the above through the preprocessor:

Code:

gcc -E 1.c
<cut>
main(int argc, char ** argv)
{
    ((256) >> 8);
}


nemobluesix 07-06-2009 05:56 AM

thanks bigearsbilly, it worked as aspire suggested.

when i said "not as expected" i meant that i asumed system returns the unaltered exit status of the command. meanwhile i read the man page of system and got a better understanding of it.

your comment is very interesting. i never used gcc to study code. i'll keep that in mind.


All times are GMT -5. The time now is 01:59 AM.