example.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. /*
  10. Threadmain spawns two subprocesses, one
  11. to read the mouse, and one to receive
  12. timer events. The events are sent via a
  13. channel to the main proc which prints a
  14. word when an event comes in. When mouse
  15. button three is pressed, the application
  16. terminates.
  17. */
  18. #include <u.h>
  19. #include <libc.h>
  20. #include <thread.h>
  21. enum
  22. {
  23. STACK = 2048,
  24. };
  25. void
  26. mouseproc(void *arg)
  27. {
  28. char m[48];
  29. int mfd;
  30. Channel *mc;
  31. mc = arg;
  32. if((mfd = open("/dev/mouse", OREAD)) < 0)
  33. sysfatal("open /dev/mouse: %r");
  34. for(;;){
  35. if(read(mfd, m, sizeof m) != sizeof m)
  36. sysfatal("eof");
  37. if(atoi(m+1+2*12)&4)
  38. sysfatal("button 3");
  39. send(mc, m);
  40. }
  41. }
  42. void
  43. clockproc(void *arg)
  44. {
  45. int t;
  46. Channel *c;
  47. c = arg;
  48. for(t=0;; t++){
  49. sleep(1000);
  50. sendul(c, t);
  51. }
  52. }
  53. void
  54. threadmain(int argc, char *argv[])
  55. {
  56. char m[48];
  57. int t;
  58. Alt a[] = {
  59. /* c v op */
  60. {nil, m, CHANRCV},
  61. {nil, &t, CHANRCV},
  62. {nil, nil, CHANEND},
  63. };
  64. /* create mouse event channel and mouse process */
  65. a[0].c = chancreate(sizeof m, 0);
  66. proccreate(mouseproc, a[0].c, STACK);
  67. /* create clock event channel and clock process */
  68. a[1].c = chancreate(sizeof(ulong), 0); /* clock event channel */
  69. proccreate(clockproc, a[1].c, STACK);
  70. for(;;){
  71. switch(alt(a)){
  72. case 0: /*mouse event */
  73. fprint(2, "click ");
  74. break;
  75. case 1: /* clock event */
  76. fprint(2, "tic ");
  77. break;
  78. default:
  79. sysfatal("can't happen");
  80. }
  81. }
  82. }