Determine Original Exit Status Code

前端 未结 2 973

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 -

相关标签:
2条回答
  • 2020-12-11 11:48

    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?)

    0 讨论(0)
  • 2020-12-11 12:06

    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"
    
    0 讨论(0)
提交回复
热议问题