fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3.  
  4. int main(int argc, char **argv) {
  5. int send[2];
  6. if(pipe(send)!=0) {
  7. perror("pipe");
  8. } else {
  9. int pid = fork();
  10. if(pid < 0) {
  11. perror("fork");
  12. }
  13. else if(pid>0) {
  14. //Parent process
  15. close(send[0]); // close pipe input
  16. dup2(send[1], 1); // replace stdout with pipe output
  17.  
  18. // send message to child
  19. fprintf(stdout, "send to child\n");
  20. fflush(stdout);
  21. } else {
  22. //Child process
  23. close(send[1]); // close pipe output
  24. dup2(send[0], 0); // replace stdin with pipe input
  25.  
  26. char message[2048];
  27. if(fgets(message, 2048, stdin) != NULL) {
  28. fprintf(stdout, "message from parent:%s", message);
  29. }
  30. }
  31. }
  32. }
Success #stdin #stdout 0s 4536KB
stdin
Standard input is empty
stdout
message from parent:send to child