execlp.c 760 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <stdlib.h>
  2. #include <unistd.h>
  3. #include <stdarg.h>
  4. extern char **environ;
  5. extern int execvep(const char *path, char *__const argv[], char *__const envp[]);
  6. int execlp(__const char *file, __const char *arg, ...)
  7. {
  8. const char *shortargv[16];
  9. const char **argv;
  10. const char *c;
  11. int i;
  12. va_list args;
  13. i = 1;
  14. va_start(args, arg);
  15. do {
  16. c = va_arg(args, const char *);
  17. i++;
  18. } while (c);
  19. va_end(args);
  20. if (i <= 16)
  21. argv = shortargv;
  22. else {
  23. argv = (const char **) malloc(sizeof(char *) * i);
  24. }
  25. argv[0] = arg;
  26. i = 1;
  27. va_start(args, arg);
  28. do {
  29. argv[i] = va_arg(args, const char *);
  30. } while (argv[i++]);
  31. va_end(args);
  32. i = execvep(file, (char *const *) argv, environ);
  33. if (argv != shortargv)
  34. free(argv);
  35. return i;
  36. }