chat.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. #include "all.h"
  2. #define SIZE 1024
  3. int chatty;
  4. int conftime;
  5. #define NSIZE 128
  6. static char nbuf[NSIZE];
  7. static int chatpid;
  8. static void
  9. killchat(void)
  10. {
  11. char buf[NSIZE];
  12. int fd;
  13. remove(nbuf);
  14. snprint(buf, sizeof buf, "/proc/%d/note", chatpid);
  15. fd = open(buf, OWRITE);
  16. write(fd, "kill\n", 5);
  17. close(fd);
  18. }
  19. void
  20. chatsrv(char *name)
  21. {
  22. int n, sfd, pfd[2];
  23. char *p, buf[256];
  24. if(name && *name)
  25. snprint(nbuf, sizeof nbuf, "/srv/%s", name);
  26. else{
  27. if(p = strrchr(argv0, '/')) /* assign = */
  28. name = p+1;
  29. else
  30. name = argv0;
  31. snprint(nbuf, sizeof nbuf, "/srv/%s.chat", name);
  32. }
  33. remove(nbuf);
  34. if(pipe(pfd) < 0)
  35. panic("chatsrv pipe");
  36. sfd = create(nbuf, OWRITE, 0600);
  37. if(sfd < 0)
  38. panic("chatsrv create %s", nbuf);
  39. chatpid = rfork(RFPROC|RFMEM);
  40. switch(chatpid){
  41. case -1:
  42. panic("chatsrv fork");
  43. case 0:
  44. break;
  45. default:
  46. atexit(killchat);
  47. return;
  48. }
  49. fprint(sfd, "%d", pfd[1]);
  50. close(sfd);
  51. close(pfd[1]);
  52. for(;;){
  53. n = read(pfd[0], buf, sizeof(buf)-1);
  54. if(n < 0)
  55. break;
  56. if(n == 0)
  57. continue;
  58. buf[n] = 0;
  59. if(buf[0] == 'c')
  60. conftime = 999;
  61. chatty = strtol(buf, 0, 0);
  62. if(abs(chatty) < 2)
  63. rpcdebug = 0;
  64. else
  65. rpcdebug = abs(chatty) - 1;
  66. fprint(2, "%s: chatty=%d, rpcdebug=%d, conftime=%d\n",
  67. nbuf, chatty, rpcdebug, conftime);
  68. }
  69. _exits(0);
  70. }
  71. void
  72. chat(char *fmt, ...)
  73. {
  74. char buf[SIZE];
  75. va_list arg;
  76. Fmt f;
  77. if(!chatty)
  78. return;
  79. fmtfdinit(&f, 2, buf, sizeof buf);
  80. va_start(arg, fmt);
  81. fmtvprint(&f, fmt, arg);
  82. va_end(arg);
  83. fmtfdflush(&f);
  84. }
  85. void
  86. clog(char *fmt, ...)
  87. {
  88. char buf[SIZE];
  89. va_list arg;
  90. int n;
  91. va_start(arg, fmt);
  92. vseprint(buf, buf+SIZE, fmt, arg);
  93. va_end(arg);
  94. n = strlen(buf);
  95. if(chatty || rpcdebug)
  96. write(2, buf, n);
  97. if(chatty <= 0){
  98. if(n>0 && buf[n-1] == '\n')
  99. buf[n-1] = 0;
  100. syslog(0, "nfs", buf);
  101. }
  102. }
  103. void
  104. panic(char *fmt, ...)
  105. {
  106. char buf[SIZE];
  107. va_list arg;
  108. va_start(arg, fmt);
  109. vseprint(buf, buf+SIZE, fmt, arg);
  110. va_end(arg);
  111. if(chatty || rpcdebug)
  112. fprint(2, "%s %d: %s: %r\n", argv0, getpid(), buf);
  113. if(chatty <= 0)
  114. syslog(0, "nfs", buf);
  115. exits("panic");
  116. }