client.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Milis Linux Ayguci Client
  3. * Milisarge - 2020
  4. * References:
  5. * http://beej.us/guide/bgipc/output/html/multipage/unixsock.html
  6. * https://github.com/baskerville/bspwm/blob/master/src/bspc.c#L88
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <errno.h>
  11. #include <string.h>
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <sys/socket.h>
  15. #include <sys/un.h>
  16. #include <unistd.h>
  17. #include <poll.h>
  18. #define SOCK_PATH "/tmp/ayguci.sock"
  19. #define BUFFSIZE 4096
  20. int main(int argc, char *argv [])
  21. {
  22. int s, t, len;
  23. struct sockaddr_un remote;
  24. char reply[BUFFSIZE];
  25. char *reqstr = argv[1];
  26. reqstr=reqstr ? reqstr : "none";
  27. if ((s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) == -1) {
  28. perror("socket");
  29. exit(1);
  30. }
  31. //printf("Trying to connect...\n");
  32. remote.sun_family = AF_UNIX;
  33. strcpy(remote.sun_path, SOCK_PATH);
  34. len = strlen(remote.sun_path) + sizeof(remote.sun_family);
  35. if (connect(s, (struct sockaddr *)&remote, len) == -1) {
  36. perror("connect");
  37. exit(1);
  38. }
  39. //printf("Connected.\n");
  40. // interactive mode - set 1 to open
  41. #if 0
  42. while(printf("> "), fgets(reply, BUFFSIZE, stdin), !feof(stdin)) {
  43. if (send(s, reply, strlen(reply), 0) == -1) {
  44. perror("send");
  45. exit(1);
  46. }
  47. if ((t=recv(s, reply, BUFFSIZE, 0)) > 0) {
  48. reply[t] = '\0';
  49. printf("echo> %s", reply);
  50. } else {
  51. if (t < 0) perror("recv");
  52. else printf("Server closed connection\n");
  53. exit(1);
  54. }
  55. }
  56. #else
  57. if (send(s, reqstr, strlen(reqstr), 0) < 0)
  58. printf("Send failed\n");
  59. //else
  60. //printf("data sent\n");
  61. struct pollfd fds[] = {
  62. {s, POLLIN, 0},
  63. {STDOUT_FILENO, POLLHUP, 0},
  64. };
  65. while (poll(fds, 2, -1) > 0) {
  66. if (fds[0].revents & POLLIN) {
  67. if ((t = recv(s, reply, sizeof(reply)-1, 0)) > 0) {
  68. reply[t] = '\0';
  69. fprintf(stdout, "%s", reply);
  70. fflush(stdout);
  71. } else {
  72. break;
  73. }
  74. }
  75. if (fds[1].revents & (POLLERR | POLLHUP)) {
  76. break;
  77. }
  78. }
  79. #endif
  80. close(s);
  81. return 0;
  82. }