popen.c 764 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. FILE *popen (const char *command, const char *modes)
  6. {
  7. int pipe_fd[2];
  8. int pid, reading;
  9. if (pipe(pipe_fd) < 0)
  10. return NULL;
  11. reading = (modes[0] == 'r');
  12. pid = vfork();
  13. if (pid < 0) {
  14. close(pipe_fd[0]);
  15. close(pipe_fd[1]);
  16. return NULL;
  17. }
  18. if (pid == 0) {
  19. close(pipe_fd[!reading]);
  20. close(reading);
  21. if (pipe_fd[reading] != reading) {
  22. dup2(pipe_fd[reading], reading);
  23. close(pipe_fd[reading]);
  24. }
  25. execl("/bin/sh", "sh", "-c", command, (char *) 0);
  26. _exit(255);
  27. }
  28. close(pipe_fd[reading]);
  29. return fdopen(pipe_fd[!reading], modes);
  30. }
  31. int pclose(FILE *fd)
  32. {
  33. int waitstat;
  34. if (fclose(fd) != 0)
  35. return EOF;
  36. wait(&waitstat);
  37. return waitstat;
  38. }