3
0

execable.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 2006 Gabriel Somlo <somlo at cmu.edu>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  8. */
  9. #include "libbb.h"
  10. /* check if path points to an executable file;
  11. * return 1 if found;
  12. * return 0 otherwise;
  13. */
  14. int execable_file(const char *name)
  15. {
  16. struct stat s;
  17. return (!access(name, X_OK) && !stat(name, &s) && S_ISREG(s.st_mode));
  18. }
  19. /* search $PATH for an executable file;
  20. * return allocated string containing full path if found;
  21. * return NULL otherwise;
  22. */
  23. char *find_execable(const char *filename)
  24. {
  25. char *path, *p, *n;
  26. p = path = xstrdup(getenv("PATH"));
  27. while (p) {
  28. n = strchr(p, ':');
  29. if (n)
  30. *n++ = '\0';
  31. if (*p != '\0') { /* it's not a PATH="foo::bar" situation */
  32. p = concat_path_file(p, filename);
  33. if (execable_file(p)) {
  34. free(path);
  35. return p;
  36. }
  37. free(p);
  38. }
  39. p = n;
  40. }
  41. free(path);
  42. return NULL;
  43. }
  44. /* search $PATH for an executable file;
  45. * return 1 if found;
  46. * return 0 otherwise;
  47. */
  48. int exists_execable(const char *filename)
  49. {
  50. char *ret = find_execable(filename);
  51. if (ret) {
  52. free(ret);
  53. return 1;
  54. }
  55. return 0;
  56. }
  57. #if ENABLE_FEATURE_PREFER_APPLETS
  58. /* just like the real execvp, but try to launch an applet named 'file' first
  59. */
  60. int bb_execvp(const char *file, char *const argv[])
  61. {
  62. return execvp(find_applet_by_name(file) ? bb_busybox_exec_path : file,
  63. argv);
  64. }
  65. #endif