Determine Original Exit Status Code

前端 未结 2 972

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

提交回复
热议问题