c/c++ unix ipc

时间:2022-07-03 08:49:55

c/c++ unix ipc

一个例子
  1. //c_unix.c
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <sys/socket.h>
  5. #include <sys/un.h>
  6. #define UNIX_DOMAIN "/tmp/UNIX.domain"
  7. int main(void)
  8. {
  9. int connect_fd;
  10. int ret;
  11. char snd_buf[1024];
  12. int i;
  13. static struct sockaddr_un srv_addr;
  14. //creat unix socket
  15. connect_fd=socket(PF_UNIX,SOCK_STREAM,0);
  16. if(connect_fd<0)
  17. {
  18. perror("cannot create communication socket");
  19. return 1;
  20. }
  21. srv_addr.sun_family=AF_UNIX;
  22. strcpy(srv_addr.sun_path,UNIX_DOMAIN);
  23. //connect server
  24. ret=connect(connect_fd,(struct sockaddr*)&srv_addr,sizeof(srv_addr));
  25. if(ret==-1)
  26. {
  27. perror("cannot connect to the server");
  28. close(connect_fd);
  29. return 1;
  30. }
  31. memset(snd_buf,0,1024);
  32. strcpy(snd_buf,"message from client");
  33. //send info server
  34. for(i=0;i<4;i++)
  35. write(connect_fd,snd_buf,sizeof(snd_buf));
  36. close(connect_fd);
  37. return 0;
  38. }
 
  1. //s_unix.c
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <sys/socket.h>
  5. #include <sys/un.h>
  6. #define UNIX_DOMAIN "/tmp/UNIX.domain"
  7. int main(void)
  8. {
  9. socklen_t clt_addr_len;
  10. int listen_fd;
  11. int com_fd;
  12. int ret;
  13. int i;
  14. static char recv_buf[1024];
  15. int len;
  16. struct sockaddr_un clt_addr;
  17. struct sockaddr_un srv_addr;
  18. listen_fd=socket(PF_UNIX,SOCK_STREAM,0);
  19. if(listen_fd<0)
  20. {
  21. perror("cannot create communication socket");
  22. return 1;
  23. }
  24. //set server addr_param
  25. srv_addr.sun_family=AF_UNIX;
  26. strncpy(srv_addr.sun_path,UNIX_DOMAIN,sizeof(srv_addr.sun_path)-1);
  27. unlink(UNIX_DOMAIN);
  28. //bind sockfd & addr
  29. ret=bind(listen_fd,(struct sockaddr*)&srv_addr,sizeof(srv_addr));
  30. if(ret==-1)
  31. {
  32. perror("cannot bind server socket");
  33. close(listen_fd);
  34. unlink(UNIX_DOMAIN);
  35. return 1;
  36. }
  37. //listen sockfd
  38. ret=listen(listen_fd,1);
  39. if(ret==-1)
  40. {
  41. perror("cannot listen the client connect request");
  42. close(listen_fd);
  43. unlink(UNIX_DOMAIN);
  44. return 1;
  45. }
  46. //have connect request use accept
  47. len=sizeof(clt_addr);
  48. com_fd=accept(listen_fd,(struct sockaddr*)&clt_addr,&len);
  49. if(com_fd<0)
  50. {
  51. perror("cannot accept client connect request");
  52. close(listen_fd);
  53. unlink(UNIX_DOMAIN);
  54. return 1;
  55. }
  56. //read and printf sent client info
  57. printf("/n=====info=====/n");
  58. for(i=0;i<4;i++)
  59. {
  60. memset(recv_buf,0,1024);
  61. int num=read(com_fd,recv_buf,sizeof(recv_buf));
  62. printf("Message from client (%d)) :%s/n",num,recv_buf);
  63. }
  64. close(com_fd);
  65. close(listen_fd);
  66. unlink(UNIX_DOMAIN);
  67. return 0;
  68. }