fork(5) download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <sys/wait.h>
  5. #include <sys/types.h>
  6.  
  7. int getcmd(char *buf, int nbuf, pid_t pid)
  8. {
  9. memset(buf, 0, nbuf);
  10. if (fgets(buf, nbuf, stdin) == NULL) {
  11. fprintf(stderr, "EOF !!!\n");
  12. return -1;
  13. }
  14. fprintf(stderr, "pid: %d -- getcmd buf ======= --> %s\n", getpid(), buf);
  15. return 0;
  16. }
  17.  
  18.  
  19. int main() {
  20.  
  21. char buf[200];
  22. int r;
  23. pid_t pid = 0;
  24.  
  25. while(getcmd(buf, 200, pid) >= 0) {
  26. fprintf(stderr, "current pid: %d\n", getpid());
  27. pid = fork();
  28. // Without forking the fgets() reads all lines normally
  29. if(pid == 0)
  30. exit(0);
  31.  
  32. wait(&r);
  33. }
  34.  
  35. return 0;
  36. }
  37.  
  38.  
  39.  
Success #stdin #stdout #stderr 0s 9432KB
stdin
One
Two
Three
stdout
Standard output is empty
stderr
pid: 32156 -- getcmd buf ======= --> One

current pid: 32156
pid: 32156 -- getcmd buf ======= --> Two

current pid: 32156
pid: 32156 -- getcmd buf ======= --> ThreeTwo

current pid: 32156
pid: 32156 -- getcmd buf ======= --> ThreeThree
current pid: 32156
EOF !!!