10.2 基于事件服务器

服务端

  1. #include <event2/event-config.h>
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <sys/queue.h>
  5. #include <unistd.h>
  6. #include <sys/time.h>
  7. #include <fcntl.h>
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <errno.h>
  12. #include <event.h>
  13. static void
  14. fifo_read(evutil_socket_t fd, short event, void *arg)
  15. {
  16. char buf[255];
  17. int len;
  18. struct event *ev = arg;
  19. /* Reschedule this event */
  20. event_add(ev, NULL);
  21. fprintf(stderr, "fifo_read called with fd: %d, event: %d, arg: %p\n",
  22. (int)fd, event, arg);
  23. len = read(fd, buf, sizeof(buf) - 1);
  24. if (len == -1) {
  25. perror("read");
  26. return;
  27. } else if (len == 0) {
  28. fprintf(stderr, "Connection closed\n");
  29. return;
  30. }
  31. buf[len] = '\0';
  32. fprintf(stdout, "Read: %s\n", buf);
  33. }
  34. int
  35. main(int argc, char **argv)
  36. {
  37. struct event evfifo;
  38. struct stat st;
  39. const char *fifo = "event.fifo";
  40. int socket;
  41. if (lstat(fifo, &st) == 0) {
  42. if ((st.st_mode & S_IFMT) == S_IFREG) {
  43. errno = EEXIST;
  44. perror("lstat");
  45. exit(1);
  46. }
  47. }
  48. unlink(fifo);
  49. if (mkfifo(fifo, 0600) == -1) {
  50. perror("mkfifo");
  51. exit(1);
  52. }
  53. /* Linux pipes are broken, we need O_RDWR instead of O_RDONLY */
  54. socket = open(fifo, O_RDONLY | O_NONBLOCK, 0);
  55. if (socket == -1) {
  56. perror("open");
  57. exit(1);
  58. }
  59. fprintf(stderr, "Write data to %s\n", fifo);
  60. /* Initalize the event library */
  61. event_init();
  62. /* Initalize one event */
  63. event_set(&evfifo, socket, EV_READ, fifo_read, &evfifo);
  64. /* Add it to the active events, without a timeout */
  65. event_add(&evfifo, NULL);
  66. event_dispatch();
  67. return (0);
  68. }

客户端

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6. #include <pthread.h>
  7. int main(int argc, char *argv[])
  8. {
  9. int fd = 0;
  10. char *str = "hello libevent!";
  11. fd = open("event.fifo", O_RDWR);
  12. if (fd < 0) {
  13. perror("open error");
  14. exit(1);
  15. }
  16. while (1) {
  17. write(fd, str, strlen(str));
  18. sleep(1);
  19. }
  20. close(fd);
  21. return 0;
  22. }