message.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #include <sys/select.h>
  7. #include <signal.h>
  8. #include <server.h>
  9. #include <message.h>
  10. #include <general.h>
  11. void init_fd_set(fd_set *fds)
  12. {
  13. GSList *l;
  14. player_t *player;
  15. FD_ZERO(fds);
  16. FD_SET(0, fds);
  17. for (l = gl_config->players ; l != NULL ; l = l->next)
  18. {
  19. player = l->data;
  20. FD_SET(player->pipe_read, fds);
  21. }
  22. }
  23. int get_max_player_fd(fd_set *fds, FILE **tab_fds)
  24. {
  25. GSList *l;
  26. player_t *player;
  27. int max = 0;
  28. fcntl(0, F_SETFL, O_NONBLOCK);
  29. tab_fds[0] = stdin;
  30. for (l = gl_config->players ; l != NULL ; l = l->next)
  31. {
  32. player = l->data;
  33. if (player->pipe_read > max)
  34. {
  35. max = player->pipe_read;
  36. }
  37. fcntl(player->pipe_read, F_SETFL, O_NONBLOCK);
  38. tab_fds[player->team_id] = fdopen(player->pipe_read, "r");
  39. }
  40. return max;
  41. }
  42. void test_file_fd(fd_set *fds, FILE **tab_fds)
  43. {
  44. GSList *l;
  45. player_t *player;
  46. char buffer[MESSAGE_BUFFER_SIZE];
  47. for (l = gl_config->players ; l != NULL ; l = l->next)
  48. {
  49. player = l->data;
  50. if (FD_ISSET(player->pipe_read, fds))
  51. {
  52. while (fgets(buffer, MESSAGE_BUFFER_SIZE,
  53. tab_fds[player->team_id]) != NULL)
  54. {
  55. if (!gl_config->quiet)
  56. {
  57. printf("<%s(%d)> %s", player->name, player->team_id, buffer);
  58. }
  59. }
  60. }
  61. }
  62. if (FD_ISSET(0, fds))
  63. {
  64. while (fgets(buffer, MESSAGE_BUFFER_SIZE, tab_fds[0]) != NULL)
  65. {
  66. printf("<server> %s", buffer);
  67. }
  68. }
  69. fflush(stdout);
  70. }
  71. static boolean_t gl_stop = False;
  72. void messager_exit(int foo)
  73. {
  74. gl_stop = True;
  75. }
  76. void launch_messager()
  77. {
  78. fd_set fds;
  79. int fd_max;
  80. FILE **tab_fds;
  81. sigprocmask(SIG_SETMASK, gl_config->mask, NULL);
  82. signal(SIGUSR1, messager_exit);
  83. tab_fds = malloc(1 + gl_config->nb_players * sizeof(FILE * ));
  84. fd_max = get_max_player_fd(&fds, tab_fds);
  85. while (!gl_stop)
  86. {
  87. init_fd_set(&fds);
  88. select(fd_max + 1, &fds, NULL, NULL, NULL);
  89. test_file_fd(&fds, tab_fds);
  90. }
  91. write(1, "\nBye!\n", 6);
  92. exit(0);
  93. }