lib_unix.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * unix_lib.c - routines for managing UNIX connections.
  3. *
  4. * Positive port/program numbers are RPC ports, negative ones are UNIX ports.
  5. *
  6. * Copyright (c) 1994-1996 Larry McVoy.
  7. */
  8. #define _LIB /* bench.h needs this */
  9. #include "bench.h"
  10. /*
  11. * Get a UNIX socket, bind it.
  12. */
  13. int
  14. unix_server(char *path)
  15. {
  16. int sock;
  17. struct sockaddr_un s;
  18. #ifdef LIBUNIX_VERBOSE
  19. fprintf(stderr, "unix_server(%s, %u)\n", prog, rdwr);
  20. #endif
  21. if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
  22. perror("socket");
  23. exit(1);
  24. }
  25. bzero((void*)&s, sizeof(s));
  26. s.sun_family = AF_UNIX;
  27. strcpy(s.sun_path, path);
  28. if (bind(sock, (struct sockaddr*)&s, sizeof(s)) < 0) {
  29. perror("bind");
  30. exit(2);
  31. }
  32. if (listen(sock, 100) < 0) {
  33. perror("listen");
  34. exit(4);
  35. }
  36. return (sock);
  37. }
  38. /*
  39. * Unadvertise the socket
  40. */
  41. int
  42. unix_done(int sock, char *path)
  43. {
  44. close(sock);
  45. unlink(path);
  46. return (0);
  47. }
  48. /*
  49. * Accept a connection and return it
  50. */
  51. int
  52. unix_accept(int sock)
  53. {
  54. struct sockaddr_un s;
  55. int newsock, namelen;
  56. namelen = sizeof(s);
  57. bzero((void*)&s, namelen);
  58. retry:
  59. if ((newsock = accept(sock, (struct sockaddr*)&s, &namelen)) < 0) {
  60. if (errno == EINTR)
  61. goto retry;
  62. perror("accept");
  63. exit(6);
  64. }
  65. return (newsock);
  66. }
  67. /*
  68. * Connect to the UNIX socket advertised as "path" and
  69. * return the connected socket.
  70. */
  71. int
  72. unix_connect(char *path)
  73. {
  74. struct sockaddr_un s;
  75. int sock;
  76. if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
  77. perror("socket");
  78. exit(1);
  79. }
  80. bzero((void*)&s, sizeof(s));
  81. s.sun_family = AF_UNIX;
  82. strcpy(s.sun_path, path);
  83. if (connect(sock, (struct sockaddr*)&s, sizeof(s)) < 0) {
  84. perror("connect");
  85. exit(4);
  86. }
  87. return (sock);
  88. }