ITEM: V0719L

How to get the exit status of a command executed by system()



ENV
AIX BOS 3.2.5

DESCRIPTION
The customer is executing the statement:
system( "ls some.file" );
and wants to know how to get the return code.

ACTION
system() returns an int like wait(), waitpid(), and wait3().
Note that the return code from the command called is not in
the least significant byte of the int which gets returned from
these functions, it's actually in the 2nd least significant
byte. The easy way to get this return code is to use the 
WEXITSTATUS macro which is defined in the file
/usr/include/sys/wait.h. If you look carefully at the macro,
it should be clear that you should not do something like this:
   int  iReturnCode;
   iReturnCode = WEXITSTATUS( system("ls some.file") );
The expansion of the WEXITSTATUS macro would cause the system()
function to be called more than once. Instead you should do
something like:
   int iWaitReturn, iReturnCode;
   iWaitReturn = system("ls some.file");
   iReturnCode = WEXITSTATUS( iWaitReturn );

SAMPLE CODE
/* system-example.c
** Insert appropriate IBM Copyright notice here
** This program demonstrates the proper use of the system() function
** and the WEXITSTATUS macro. When called from the command line with
** no arguments, it forks and execs a copy of itself through the 
** system() function. This child process is called with an argument
** which is used as an exit code.
*/

\#define MAX_BUF 80

\#include \
\#include \
\#include \
\#include \

main( int argc, char *argv[] ) {
   if( argc == 1 ) {
      char cpBuffer[ MAX_BUF ];
      int  iWaitReturn;
      int  iReturnCode;

      printf( "Parent: Starting\\n");
      strncpy( cpBuffer, argv[0], MAX_BUF - 3 );
      strcat( cpBuffer, " 24");
      printf( "Parent: Executing Command %s\\n", cpBuffer );

      iWaitReturn = system( cpBuffer );
      printf( "Parent: Received %08X as a return value\\n", iWaitReturn );
      iReturnCode = WEXITSTATUS( iWaitReturn );
      printf( "Parent: Child's exit status was %d\\n", iReturnCode );
      exit(0);
   } else {
      int iExitCode;

      printf( "Child : Starting\\n" );
      iExitCode = atoi( argv[1] );
      printf( "Child : Attempting to exit with exit code %d.\\n", iExitCode );
      exit( iExitCode );
   }


Support Line: How to get the exit status of a command executed by system() ITEM: V0719L
Dated: June 1995 Category: N/A
This HTML file was generated 99/06/24~13:30:34
Comments or suggestions? Contact us