简体   繁体   中英

collect return/exit status of process using system call in Linux

I am trying to collect the return status of process launched through call system() . sample is the child process with return status of 100, that i want to collect in launcher . But what i am getting is a different value 256 for exit(1); and 51200 for exit(200)

Is there any relation between the exit value from sample and printed value from launcher ? How can i properly collect exit value from child to parent.

sample.c: gcc sample.c -o sample

#include <stdio.h>
#include <stdlib.h>
//#include <errno.h>
//extern int errno;
int main()
{
 
        printf("hello\n");
  //      errno = 100;
  //      exit(-1); or
  //      exit(1);
       exit(100);
}

launcher.c: parent process

#include <stdio.h>
int main()
{
        int rval ;
        rval =system("./sample");
        printf("rval from sample: %d\n", rval);
        return 0;
}

UPDATE 1: Actually if i use printf("rval from sample: %d\n", WEXITSTATUS(rval)); its working on gcc but not on my cross-compiler.

On my cross compiler if i add exit(WEXITSTATUS(100));in sample.c, I am getting proper value to my launcher, no need to use WEXITSTATUS in launcher.

Is that ok?

Update 2: Can anybody please let me know do we need to set errnum to be able to collect the return value of process using system call. because i am not getting actual return value from the called process, if i return somevalue.

what i mean is inside called process something like

errno = retval;
return ratval

and in the caller process

retval = system(someprocess);
WEXITSTATUS(retval);

system does not literally return the exit status of the other program; what it actually returns is described in its man page :

The value returned is -1 on error (eg, fork(2) failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2) . Thus, the exit code of the command will be WEXITSTATUS(status) .

The exact format of the returned integer is not specified in the wait(2) man page. I'm not sure if it's standardized in POSIX, but one should just use the provided macros in any case.

So, presuming you don't care about error checking, this should give you the expected result:

    printf("rval from sample: %d\n", WEXITSTATUS(rval));

Change:

     printf("rval from sample: %d\n", rval);

To:

    if (rval >= 0)
        printf("rval from sample: %d\n", WEXITSTATUS(rval));
    else
        perror("Unable to launch sample");

Note that this is platform specific according to C. The code above should work on all POSIX systems such as Linux. POSIX says that the return from system must match waitpid which must have this behavior .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM