3
0

execable.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. }