socketpair.c 779 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <sys/socket.h>
  7. #include <sys/wait.h>
  8. int main(int argc, char ** argv)
  9. {
  10. int sv[2];
  11. socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
  12. int pid1 = fork();
  13. if (pid1 < 0) {
  14. printf("fork failed\n");
  15. return -1;
  16. }
  17. if (pid1 == 0) {
  18. close(sv[0]);
  19. write(sv[1], "hello world",12);
  20. return 0;
  21. }
  22. char buffer[20];
  23. int bytes;
  24. close(sv[1]);
  25. bytes = read(sv[0], buffer, 12);
  26. buffer[bytes] = 0;
  27. printf("%s\n", buffer);
  28. waitpid(pid1, NULL, 0);
  29. return 0;
  30. }