socketpair.c 655 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. if (write(sv[1], "hello world", 12) != 12) {
  17. return 1;
  18. }
  19. return 0;
  20. }
  21. char buffer[20];
  22. int bytes;
  23. close(sv[1]);
  24. bytes = read(sv[0], buffer, 12);
  25. buffer[bytes] = 0;
  26. printf("%s\n", buffer);
  27. waitpid(pid1, NULL, 0);
  28. return 0;
  29. }