system.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
  3. * See the copyright notice in the ACK home directory, in the file "Copyright".
  4. */
  5. /* $Id$ */
  6. #if defined(_POSIX_SOURCE)
  7. #include <sys/types.h>
  8. #endif
  9. #include <stdlib.h>
  10. #include <signal.h>
  11. extern int _fork(void);
  12. extern int _wait(int *);
  13. extern void _exit(int);
  14. extern void _execve(const char *path, const char ** argv, const char ** envp);
  15. extern void _close(int);
  16. #define FAIL 127
  17. extern const char **_penvp;
  18. static const char *exec_tab[] = {
  19. "sh", /* argv[0] */
  20. "-c", /* argument to the shell */
  21. NULL, /* to be filled with user command */
  22. NULL /* terminating NULL */
  23. };
  24. int
  25. system(const char *str)
  26. {
  27. int pid, exitstatus, waitval;
  28. int i;
  29. if ((pid = _fork()) < 0) return str ? -1 : 0;
  30. if (pid == 0) {
  31. for (i = 3; i <= 20; i++)
  32. _close(i);
  33. if (!str) str = "cd ."; /* just testing for a shell */
  34. exec_tab[2] = str; /* fill in command */
  35. _execve("/bin/sh", exec_tab, _penvp);
  36. /* get here if execve fails ... */
  37. _exit(FAIL); /* see manual page */
  38. }
  39. while ((waitval = _wait(&exitstatus)) != pid) {
  40. if (waitval == -1) break;
  41. }
  42. if (waitval == -1) {
  43. /* no child ??? or maybe interrupted ??? */
  44. exitstatus = -1;
  45. }
  46. if (!str) {
  47. if (exitstatus == FAIL << 8) /* execve() failed */
  48. exitstatus = 0;
  49. else exitstatus = 1; /* /bin/sh exists */
  50. }
  51. return exitstatus;
  52. }