socketpair.c 611 B

123456789101112131415161718192021222324252627282930313233343536
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/socket.h>
  4. #include <sys/wait.h>
  5. #include <unistd.h>
  6. int main(int argc, char** argv) {
  7. int sv[2];
  8. socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
  9. int pid1 = fork();
  10. if (pid1 < 0) {
  11. printf("fork failed\n");
  12. return -1;
  13. }
  14. if (pid1 == 0) {
  15. close(sv[0]);
  16. write(sv[1], "hello world", 12);
  17. return 0;
  18. }
  19. char buffer[20];
  20. int bytes;
  21. close(sv[1]);
  22. bytes = read(sv[0], buffer, 12);
  23. buffer[bytes] = 0;
  24. printf("%s\n", buffer);
  25. waitpid(pid1, NULL, 0);
  26. return 0;
  27. }