popen.c 759 B

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