xsystem.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* xsystem.c - system(3) with error messages
  2. Carl D. Worth
  3. Copyright (C) 2001 University of Southern California
  4. This program is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU General Public License as
  6. published by the Free Software Foundation; either version 2, or (at
  7. your option) any later version.
  8. This program is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. */
  13. #include <sys/types.h>
  14. #include <sys/wait.h>
  15. #include <unistd.h>
  16. #include "xsystem.h"
  17. #include "libbb/libbb.h"
  18. /* Like system(3), but with error messages printed if the fork fails
  19. or if the child process dies due to an uncaught signal. Also, the
  20. return value is a bit simpler:
  21. -1 if there was any problem
  22. Otherwise, the 8-bit return value of the program ala WEXITSTATUS
  23. as defined in <sys/wait.h>.
  24. */
  25. int xsystem(const char *argv[])
  26. {
  27. int status;
  28. pid_t pid;
  29. pid = vfork();
  30. switch (pid) {
  31. case -1:
  32. opkg_perror(ERROR, "%s: vfork", argv[0]);
  33. return -1;
  34. case 0:
  35. /* child */
  36. execvp(argv[0], (char *const *)argv);
  37. _exit(-1);
  38. default:
  39. /* parent */
  40. break;
  41. }
  42. if (waitpid(pid, &status, 0) == -1) {
  43. opkg_perror(ERROR, "%s: waitpid", argv[0]);
  44. return -1;
  45. }
  46. if (WIFSIGNALED(status)) {
  47. opkg_msg(ERROR, "%s: Child killed by signal %d.\n",
  48. argv[0], WTERMSIG(status));
  49. return -1;
  50. }
  51. if (!WIFEXITED(status)) {
  52. /* shouldn't happen */
  53. opkg_msg(ERROR, "%s: Your system is broken: got status %d "
  54. "from waitpid.\n", argv[0], status);
  55. return -1;
  56. }
  57. return WEXITSTATUS(status);
  58. }