Determine Original Exit Status Code

≯℡__Kan透↙ 提交于 2019-11-28 12:53:37

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"

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!