Determine Original Exit Status Code

2019-01-20 04:38发布

问题:

In a software baseline I am maintaining, there are 150 statements spread out amongst various C applications that make a call to either another Linux command (e.g. rm -rf ...) or custom application using status = system(cmd)/256. When either is called, the status code returned from either the Linux command or custom application is divided by 256. So that when the status code is greater than 0, we know there was a problem. However, the way the software was written, it doesn't always log what command or application returned the status code. So that if the status code was say 32768, when divided by 256, the status code reported is 128.

The software is old and while I could make changes, it would be nice if any of the commands called or applications called reported their original status code elsewhere.

Is there a way to determine the original status code in a standard Linux log file and the application which returned it?

回答1:

How to write a wrapper

Following an example on how to apply a wrapper around the libc function system().

Create a new module (translation units) called system_wrapper.c like so:

The header system_wrapper.h:

#ifndef _SYSTEM_WRAPPER
#define _SYSTEM_WRAPPER

#define system(cmd) system_wrapper(cmd)

int system_wrapper(const char *);

#endif

The module system_wrapper.c:

#include <stdlib.h> /* to prototype the original function, that is libc's system() */
#include "system_wrapper.h"

#undef system

int system_wrapper(const char * cmd)
{
  int result = system(cmd);

  /* Log result here. */

  return result;
}

Add this line to all modules using system():

#include "system_wrapper.h"


回答2:

As I commented, system(3) library function returns the result of a waiting syscall like waitpid(2). (Please follow the links to the man pages).

So you should improve your program to use WIFEXITED, WIFSIGNALED, WEXITSTATUS, WTERMSIG standard (Posix) macros on the result of calls to system (except when that result is -1, then use errno).

Coding

 status = system(cmd)/256;

is unreadable (to the human developer) and unportable.

I guess the coder who coded that wanted to catch interrupted commands....

You should replace that with

 status = system(cmd);
 if (status < 0) /* e.g. fork failed */
   do_something_with_error_code (errno);
 else if (status == 0) /* cmd run without errors */
   do_something_to_tell_command_exited_ok ();
 else if (WIFEXITED(status)) /* cmd got an error */
   do_something_with_exit_code (WEXITSTATUS(status));
 else if (WIFSIGNALED(status))  /* cmd or the shell got a signal */
   do_something_with_terminating_signal (WTERMSIG(status));

BTW, using system("rm -rf /some/dir"); is considered bad practice (what if the user made his own rm in his $PATH) and not very efficient. (You could for example use nftw(3) with unlink(2)) or at least /bin/rm -rf ; but what about spaces in the directory name or dirty IFS tricks?)