Debian Codegraph @

pTk/mTk/tclUnix/tclUnixNotfy.c

raw symbols SCIP
1 /*
2 * tclUnixNotify.c --
3 *
4 * This file contains the implementation of the select-based
5 * Unix-specific notifier, which is the lowest-level part of the
6 * Tcl event loop. This file works together with
7 * ../generic/tclNotify.c.
8 *
9 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
10 *
11 * See the file "license.terms" for information on usage and redistribution
12 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13 *
14 * RCS: @(#) $Id: tclUnixNotfy.c,v 1.11.2.2 2003/07/16 22:09:48 hobbs Exp $
15 */
16
17 #if 0
18 #include "tclInt.h"
19 #include "tclPort.h"
20 #else
21 #include "tkPort.h"
22 #include "Lang.h"
23 #endif
24 #include <signal.h>
25 #ifdef _LANG
26 #include <errno.h>
27 #endif
28
29 #ifdef TCL_EVENT_IMPLEMENT
30
31 #ifndef _LANG
32 extern TclStubs tclStubs;
33 #else
34 #include "tkEvent_f.h"
35 #endif
36 extern Tcl_NotifierProcs tclOriginalNotifier;
37
38 #ifndef MASK_SIZE
39 /* under Cygwin we use tclUnix but tkWin.
40 So bring in some "tkUnixPort.h" definitions
41 */
42 #ifdef HAVE_SYS_SELECT_H
43 # include <sys/select.h>
44 #endif
45
46 /*
47 * The following macro defines the number of fd_masks in an fd_set:
48 */
49
50 #ifndef FD_SETSIZE
51 # ifdef OPEN_MAX
52 # define FD_SETSIZE OPEN_MAX
53 # else
54 # define FD_SETSIZE 256
55 # endif
56 #endif
57 #if !defined(howmany)
58 # define howmany(x, y) (((x)+((y)-1))/(y))
59 #endif
60 #ifndef NFDBITS
61 # define NFDBITS NBBY*sizeof(fd_mask)
62 #endif
63 #define MASK_SIZE howmany(FD_SETSIZE, NFDBITS)
64 #endif
65
66 /*
67 * This structure is used to keep track of the notifier info for a
68 * a registered file.
69 */
70
71 typedef struct FileHandler {
72 int fd;
73 int mask; /* Mask of desired events: TCL_READABLE,
74 * etc. */
75 int readyMask; /* Mask of events that have been seen since the
76 * last time file handlers were invoked for
77 * this file. */
78 Tcl_FileProc *proc; /* Procedure to call, in the style of
79 * Tcl_CreateFileHandler. */
80 ClientData clientData; /* Argument to pass to proc. */
81 struct FileHandler *nextPtr;/* Next in list of all files we care about. */
82 } FileHandler;
83
84 /*
85 * The following structure is what is added to the Tcl event queue when
86 * file handlers are ready to fire.
87 */
88
89 typedef struct FileHandlerEvent {
90 Tcl_Event header; /* Information that is standard for
91 * all events. */
92 int fd; /* File descriptor that is ready. Used
93 * to find the FileHandler structure for
94 * the file (can't point directly to the
95 * FileHandler structure because it could
96 * go away while the event is queued). */
97 } FileHandlerEvent;
98
99 /*
100 *
101 * The following structure contains a set of select() masks to track
102 * readable, writable, and exceptional conditions.
103 */
104
105 typedef struct SelectMasks {
106 fd_set readable;
107 fd_set writable;
108 fd_set exceptional;
109 } SelectMasks;
110
111 /*
112 * The following static structure contains the state information for the
113 * select based implementation of the Tcl notifier. One of these structures
114 * is created for each thread that is using the notifier.
115 */
116
117 typedef struct ThreadSpecificData {
118 FileHandler *firstFileHandlerPtr;
119 /* Pointer to head of file handler list. */
120
121 SelectMasks checkMasks; /* This structure is used to build up the masks
122 * to be used in the next call to select.
123 * Bits are set in response to calls to
124 * Tcl_CreateFileHandler. */
125 SelectMasks readyMasks; /* This array reflects the readable/writable
126 * conditions that were found to exist by the
127 * last call to select. */
128 int numFdBits; /* Number of valid bits in checkMasks
129 * (one more than highest fd for which
130 * Tcl_WatchFile has been called). */
131 #ifdef TCL_THREADS
132 int onList; /* True if it is in this list */
133 unsigned int pollState; /* pollState is used to implement a polling
134 * handshake between each thread and the
135 * notifier thread. Bits defined below. */
136 struct ThreadSpecificData *nextPtr, *prevPtr;
137 /* All threads that are currently waiting on
138 * an event have their ThreadSpecificData
139 * structure on a doubly-linked listed formed
140 * from these pointers. You must hold the
141 * notifierMutex lock before accessing these
142 * fields. */
143 Tcl_Condition waitCV; /* Any other thread alerts a notifier
144 * that an event is ready to be processed
145 * by signaling this condition variable. */
146 int eventReady; /* True if an event is ready to be processed.
147 * Used as condition flag together with
148 * waitCV above. */
149 #endif
150 } ThreadSpecificData;
151
152 static Tcl_ThreadDataKey dataKey;
153
154 #ifdef TCL_THREADS
155 /*
156 * The following static indicates the number of threads that have
157 * initialized notifiers.
158 *
159 * You must hold the notifierMutex lock before accessing this variable.
160 */
161
162 static int notifierCount = 0;
163
164 /*
165 * The following variable points to the head of a doubly-linked list of
166 * of ThreadSpecificData structures for all threads that are currently
167 * waiting on an event.
168 *
169 * You must hold the notifierMutex lock before accessing this list.
170 */
171
172 static ThreadSpecificData *waitingListPtr = NULL;
173
174 /*
175 * The notifier thread spends all its time in select() waiting for a
176 * file descriptor associated with one of the threads on the waitingListPtr
177 * list to do something interesting. But if the contents of the
178 * waitingListPtr list ever changes, we need to wake up and restart
179 * the select() system call. You can wake up the notifier thread by
180 * writing a single byte to the file descriptor defined below. This
181 * file descriptor is the input-end of a pipe and the notifier thread is
182 * listening for data on the output-end of the same pipe. Hence writing
183 * to this file descriptor will cause the select() system call to return
184 * and wake up the notifier thread.
185 *
186 * You must hold the notifierMutex lock before accessing this list.
187 */
188
189 static int triggerPipe = -1;
190
191 /*
192 * The notifierMutex locks access to all of the global notifier state.
193 */
194
195 TCL_DECLARE_MUTEX(notifierMutex)
196
197 /*
198 * The notifier thread signals the notifierCV when it has finished
199 * initializing the triggerPipe and right before the notifier
200 * thread terminates.
201 */
202
203 static Tcl_Condition notifierCV;
204
205 /*
206 * The pollState bits
207 * POLL_WANT is set by each thread before it waits on its condition
208 * variable. It is checked by the notifier before it does
209 * select.
210 * POLL_DONE is set by the notifier if it goes into select after
211 * seeing POLL_WANT. The idea is to ensure it tries a select
212 * with the same bits the initial thread had set.
213 */
214 #define POLL_WANT 0x1
215 #define POLL_DONE 0x2
216
217 /*
218 * This is the thread ID of the notifier thread that does select.
219 */
220 static Tcl_ThreadId notifierThread;
221
222 #endif
223
224 /*
225 * Static routines defined in this file.
226 */
227
228 #ifdef TCL_THREADS
229 static void NotifierThreadProc _ANSI_ARGS_((ClientData clientData));
230 #endif
231 static int FileHandlerEventProc _ANSI_ARGS_((Tcl_Event *evPtr,
232 int flags));
233
234 /*
235 *----------------------------------------------------------------------
236 *
237 * Tcl_InitNotifier --
238 *
239 * Initializes the platform specific notifier state.
240 *
241 * Results:
242 * Returns a handle to the notifier state for this thread..
243 *
244 * Side effects:
245 * None.
246 *
247 *----------------------------------------------------------------------
248 */
249
250 ClientData
251 Tcl_InitNotifier()
252 {
253 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
254
255 #ifdef TCL_THREADS
256 tsdPtr->eventReady = 0;
257
258 /*
259 * Start the Notifier thread if necessary.
260 */
261
262 Tcl_MutexLock(&notifierMutex);
263 if (notifierCount == 0) {
264 if (Tcl_CreateThread(&notifierThread, NotifierThreadProc, NULL,
265 TCL_THREAD_STACK_DEFAULT, TCL_THREAD_NOFLAGS) != TCL_OK) {
266 panic("Tcl_InitNotifier: unable to start notifier thread");
267 }
268 }
269 notifierCount++;
270
271 /*
272 * Wait for the notifier pipe to be created.
273 */
274
275 while (triggerPipe < 0) {
276 Tcl_ConditionWait(&notifierCV, &notifierMutex, NULL);
277 }
278
279 Tcl_MutexUnlock(&notifierMutex);
280 #endif
281 return (ClientData) tsdPtr;
282 }
283
284 /*
285 *----------------------------------------------------------------------
286 *
287 * Tcl_FinalizeNotifier --
288 *
289 * This function is called to cleanup the notifier state before
290 * a thread is terminated.
291 *
292 * Results:
293 * None.
294 *
295 * Side effects:
296 * May terminate the background notifier thread if this is the
297 * last notifier instance.
298 *
299 *----------------------------------------------------------------------
300 */
301
302 void
303 Tcl_FinalizeNotifier(clientData)
304 ClientData clientData; /* Not used. */
305 {
306 #ifdef TCL_THREADS
307 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
308
309 Tcl_MutexLock(&notifierMutex);
310 notifierCount--;
311
312 /*
313 * If this is the last thread to use the notifier, close the notifier
314 * pipe and wait for the background thread to terminate.
315 */
316
317 if (notifierCount == 0) {
318 if (triggerPipe < 0) {
319 panic("Tcl_FinalizeNotifier: notifier pipe not initialized");
320 }
321
322 /*
323 * Send "q" message to the notifier thread so that it will
324 * terminate. The notifier will return from its call to select()
325 * and notice that a "q" message has arrived, it will then close
326 * its side of the pipe and terminate its thread. Note the we can
327 * not just close the pipe and check for EOF in the notifier
328 * thread because if a background child process was created with
329 * exec, select() would not register the EOF on the pipe until the
330 * child processes had terminated. [Bug: 4139]
331 */
332 write(triggerPipe, "q", 1);
333 close(triggerPipe);
334
335 Tcl_ConditionWait(&notifierCV, &notifierMutex, NULL);
336 }
337
338 /*
339 * Clean up any synchronization objects in the thread local storage.
340 */
341
342 Tcl_ConditionFinalize(&(tsdPtr->waitCV));
343
344 Tcl_MutexUnlock(&notifierMutex);
345 #endif
346 }
347
348 /*
349 *----------------------------------------------------------------------
350 *
351 * Tcl_AlertNotifier --
352 *
353 * Wake up the specified notifier from any thread. This routine
354 * is called by the platform independent notifier code whenever
355 * the Tcl_ThreadAlert routine is called. This routine is
356 * guaranteed not to be called on a given notifier after
357 * Tcl_FinalizeNotifier is called for that notifier.
358 *
359 * Results:
360 * None.
361 *
362 * Side effects:
363 * Signals the notifier condition variable for the specified
364 * notifier.
365 *
366 *----------------------------------------------------------------------
367 */
368
369 void
370 Tcl_AlertNotifier(clientData)
371 ClientData clientData;
372 {
373 #ifdef TCL_THREADS
374 ThreadSpecificData *tsdPtr = (ThreadSpecificData *) clientData;
375 Tcl_MutexLock(&notifierMutex);
376 tsdPtr->eventReady = 1;
377 Tcl_ConditionNotify(&tsdPtr->waitCV);
378 Tcl_MutexUnlock(&notifierMutex);
379 #endif
380 }
381
382 /*
383 *----------------------------------------------------------------------
384 *
385 * Tcl_SetTimer --
386 *
387 * This procedure sets the current notifier timer value. This
388 * interface is not implemented in this notifier because we are
389 * always running inside of Tcl_DoOneEvent.
390 *
391 * Results:
392 * None.
393 *
394 * Side effects:
395 * None.
396 *
397 *----------------------------------------------------------------------
398 */
399
400 void
401 Tcl_SetTimer(timePtr)
402 Tcl_Time *timePtr; /* Timeout value, may be NULL. */
403 {
404 /*
405 * The interval timer doesn't do anything in this implementation,
406 * because the only event loop is via Tcl_DoOneEvent, which passes
407 * timeout values to Tcl_WaitForEvent.
408 */
409
410 if (tclStubs.tcl_SetTimer != tclOriginalNotifier.setTimerProc) {
411 tclStubs.tcl_SetTimer(timePtr);
412 }
413 }
414
415 /*
416 *----------------------------------------------------------------------
417 *
418 * Tcl_ServiceModeHook --
419 *
420 * This function is invoked whenever the service mode changes.
421 *
422 * Results:
423 * None.
424 *
425 * Side effects:
426 * None.
427 *
428 *----------------------------------------------------------------------
429 */
430
431 void
432 Tcl_ServiceModeHook(mode)
433 int mode; /* Either TCL_SERVICE_ALL, or
434 * TCL_SERVICE_NONE. */
435 {
436 }
437
438 /*
439 *----------------------------------------------------------------------
440 *
441 * Tcl_CreateFileHandler --
442 *
443 * This procedure registers a file handler with the select notifier.
444 *
445 * Results:
446 * None.
447 *
448 * Side effects:
449 * Creates a new file handler structure.
450 *
451 *----------------------------------------------------------------------
452 */
453
454 void
455 Tcl_CreateFileHandler(fd, mask, proc, clientData)
456 int fd; /* Handle of stream to watch. */
457 int mask; /* OR'ed combination of TCL_READABLE,
458 * TCL_WRITABLE, and TCL_EXCEPTION:
459 * indicates conditions under which
460 * proc should be called. */
461 Tcl_FileProc *proc; /* Procedure to call for each
462 * selected event. */
463 ClientData clientData; /* Arbitrary data to pass to proc. */
464 {
465 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
466 FileHandler *filePtr;
467
468 if (tclStubs.tcl_CreateFileHandler != tclOriginalNotifier.createFileHandlerProc) {
469 tclStubs.tcl_CreateFileHandler(fd, mask, proc, clientData);
470 return;
471 }
472
473 for (filePtr = tsdPtr->firstFileHandlerPtr; filePtr != NULL;
474 filePtr = filePtr->nextPtr) {
475 if (filePtr->fd == fd) {
476 break;
477 }
478 }
479 if (filePtr == NULL) {
480 filePtr = (FileHandler*) ckalloc(sizeof(FileHandler));
481 filePtr->fd = fd;
482 filePtr->readyMask = 0;
483 filePtr->nextPtr = tsdPtr->firstFileHandlerPtr;
484 tsdPtr->firstFileHandlerPtr = filePtr;
485 }
486 filePtr->proc = proc;
487 filePtr->clientData = clientData;
488 filePtr->mask = mask;
489
490 /*
491 * Update the check masks for this file.
492 */
493
494 if ( mask & TCL_READABLE ) {
495 FD_SET( fd, &(tsdPtr->checkMasks.readable) );
496 } else {
497 FD_CLR( fd, &(tsdPtr->checkMasks.readable) );
498 }
499 if ( mask & TCL_WRITABLE ) {
500 FD_SET( fd, &(tsdPtr->checkMasks.writable) );
501 } else {
502 FD_CLR( fd, &(tsdPtr->checkMasks.writable) );
503 }
504 if ( mask & TCL_EXCEPTION ) {
505 FD_SET( fd, &(tsdPtr->checkMasks.exceptional) );
506 } else {
507 FD_CLR( fd, &(tsdPtr->checkMasks.exceptional) );
508 }
509 if (tsdPtr->numFdBits <= fd) {
510 tsdPtr->numFdBits = fd+1;
511 }
512 }
513
514 /*
515 *----------------------------------------------------------------------
516 *
517 * Tcl_DeleteFileHandler --
518 *
519 * Cancel a previously-arranged callback arrangement for
520 * a file.
521 *
522 * Results:
523 * None.
524 *
525 * Side effects:
526 * If a callback was previously registered on file, remove it.
527 *
528 *----------------------------------------------------------------------
529 */
530
531 void
532 Tcl_DeleteFileHandler(fd)
533 int fd; /* Stream id for which to remove callback procedure. */
534 {
535 FileHandler *filePtr, *prevPtr;
536 int i;
537 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
538
539 if (tclStubs.tcl_DeleteFileHandler != tclOriginalNotifier.deleteFileHandlerProc) {
540 tclStubs.tcl_DeleteFileHandler(fd);
541 return;
542 }
543
544 /*
545 * Find the entry for the given file (and return if there isn't one).
546 */
547
548 for (prevPtr = NULL, filePtr = tsdPtr->firstFileHandlerPtr; ;
549 prevPtr = filePtr, filePtr = filePtr->nextPtr) {
550 if (filePtr == NULL) {
551 return;
552 }
553 if (filePtr->fd == fd) {
554 break;
555 }
556 }
557
558 /*
559 * Update the check masks for this file.
560 */
561
562 if (filePtr->mask & TCL_READABLE) {
563 FD_CLR( fd, &(tsdPtr->checkMasks.readable) );
564 }
565 if (filePtr->mask & TCL_WRITABLE) {
566 FD_CLR( fd, &(tsdPtr->checkMasks.writable) );
567 }
568 if (filePtr->mask & TCL_EXCEPTION) {
569 FD_CLR( fd, &(tsdPtr->checkMasks.exceptional) );
570 }
571
572 /*
573 * Find current max fd.
574 */
575
576 if (fd+1 == tsdPtr->numFdBits) {
577 tsdPtr->numFdBits = 0;
578 for (i = fd-1; i >= 0; i--) {
579 if ( FD_ISSET( i, &(tsdPtr->checkMasks.readable) )
580 || FD_ISSET( i, &(tsdPtr->checkMasks.writable) )
581 || FD_ISSET( i, &(tsdPtr->checkMasks.exceptional ) ) ) {
582 tsdPtr->numFdBits = i+1;
583 break;
584 }
585 }
586 }
587
588 /*
589 * Clean up information in the callback record.
590 */
591
592 if (prevPtr == NULL) {
593 tsdPtr->firstFileHandlerPtr = filePtr->nextPtr;
594 } else {
595 prevPtr->nextPtr = filePtr->nextPtr;
596 }
597 ckfree((char *) filePtr);
598 }
599
600
601 #if defined(__EMX__) && (defined(__WIN32__) || defined(__PM__))
602 /* Backdoor into processing of events when from Tk. */
603 int (*Tcl_WaitForEventProc)(int, fd_mask *, Tcl_Time *) = NULL;
604 #endif
605 /*
606 *----------------------------------------------------------------------
607 *
608 * FileHandlerEventProc --
609 *
610 * This procedure is called by Tcl_ServiceEvent when a file event
611 * reaches the front of the event queue. This procedure is
612 * responsible for actually handling the event by invoking the
613 * callback for the file handler.
614 *
615 * Results:
616 * Returns 1 if the event was handled, meaning it should be removed
617 * from the queue. Returns 0 if the event was not handled, meaning
618 * it should stay on the queue. The only time the event isn't
619 * handled is if the TCL_FILE_EVENTS flag bit isn't set.
620 *
621 * Side effects:
622 * Whatever the file handler's callback procedure does.
623 *
624 *----------------------------------------------------------------------
625 */
626
627 static int
628 FileHandlerEventProc(evPtr, flags)
629 Tcl_Event *evPtr; /* Event to service. */
630 int flags; /* Flags that indicate what events to
631 * handle, such as TCL_FILE_EVENTS. */
632 {
633 int mask;
634 FileHandler *filePtr;
635 FileHandlerEvent *fileEvPtr = (FileHandlerEvent *) evPtr;
636 ThreadSpecificData *tsdPtr;
637
638 if (!(flags & TCL_FILE_EVENTS)) {
639 return 0;
640 }
641
642 /*
643 * Search through the file handlers to find the one whose handle matches
644 * the event. We do this rather than keeping a pointer to the file
645 * handler directly in the event, so that the handler can be deleted
646 * while the event is queued without leaving a dangling pointer.
647 */
648
649 tsdPtr = TCL_TSD_INIT(&dataKey);
650 for (filePtr = tsdPtr->firstFileHandlerPtr; filePtr != NULL;
651 filePtr = filePtr->nextPtr) {
652 if (filePtr->fd != fileEvPtr->fd) {
653 continue;
654 }
655
656 /*
657 * The code is tricky for two reasons:
658 * 1. The file handler's desired events could have changed
659 * since the time when the event was queued, so AND the
660 * ready mask with the desired mask.
661 * 2. The file could have been closed and re-opened since
662 * the time when the event was queued. This is why the
663 * ready mask is stored in the file handler rather than
664 * the queued event: it will be zeroed when a new
665 * file handler is created for the newly opened file.
666 */
667
668 mask = filePtr->readyMask & filePtr->mask;
669 filePtr->readyMask = 0;
670 if (mask != 0) {
671 (*filePtr->proc)(filePtr->clientData, mask);
672 }
673 break;
674 }
675 return 1;
676 }
677
678 /*
679 *----------------------------------------------------------------------
680 *
681 * Tcl_WaitForEvent --
682 *
683 * This function is called by Tcl_DoOneEvent to wait for new
684 * events on the message queue. If the block time is 0, then
685 * Tcl_WaitForEvent just polls without blocking.
686 *
687 * Results:
688 * Returns -1 if the select would block forever, otherwise
689 * returns 0.
690 *
691 * Side effects:
692 * Queues file events that are detected by the select.
693 *
694 *----------------------------------------------------------------------
695 */
696
697 int
698 Tcl_WaitForEvent(timePtr)
699 Tcl_Time *timePtr; /* Maximum block time, or NULL. */
700 {
701 FileHandler *filePtr;
702 FileHandlerEvent *fileEvPtr;
703 struct timeval timeout, *timeoutPtr;
704 int mask;
705 #ifdef TCL_THREADS
706 int waitForFiles;
707 #else
708 int numFound;
709 #endif
710 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
711
712 if (tclStubs.tcl_WaitForEvent != tclOriginalNotifier.waitForEventProc) {
713 return tclStubs.tcl_WaitForEvent(timePtr);
714 }
715
716 /*
717 * Set up the timeout structure. Note that if there are no events to
718 * check for, we return with a negative result rather than blocking
719 * forever.
720 */
721
722 if (timePtr) {
723 timeout.tv_sec = timePtr->sec;
724 timeout.tv_usec = timePtr->usec;
725 timeoutPtr = &timeout;
726 #ifndef TCL_THREADS
727 } else if (tsdPtr->numFdBits == 0) {
728 /*
729 * If there are no threads, no timeout, and no fds registered,
730 * then there are no events possible and we must avoid deadlock.
731 * Note that this is not entirely correct because there might
732 * be a signal that could interrupt the select call, but we
733 * don't handle that case if we aren't using threads.
734 */
735
736 return -1;
737 #endif
738 } else {
739 timeoutPtr = NULL;
740 }
741
742 #ifdef TCL_THREADS
743 /*
744 * Place this thread on the list of interested threads, signal the
745 * notifier thread, and wait for a response or a timeout.
746 */
747
748 Tcl_MutexLock(&notifierMutex);
749
750 waitForFiles = (tsdPtr->numFdBits > 0);
751 if (timePtr != NULL && timePtr->sec == 0 && timePtr->usec == 0) {
752 /*
753 * Cannot emulate a polling select with a polling condition variable.
754 * Instead, pretend to wait for files and tell the notifier
755 * thread what we are doing. The notifier thread makes sure
756 * it goes through select with its select mask in the same state
757 * as ours currently is. We block until that happens.
758 */
759
760 waitForFiles = 1;
761 tsdPtr->pollState = POLL_WANT;
762 timePtr = NULL;
763 } else {
764 tsdPtr->pollState = 0;
765 }
766
767 if (waitForFiles) {
768 /*
769 * Add the ThreadSpecificData structure of this thread to the list
770 * of ThreadSpecificData structures of all threads that are waiting
771 * on file events.
772 */
773
774
775 tsdPtr->nextPtr = waitingListPtr;
776 if (waitingListPtr) {
777 waitingListPtr->prevPtr = tsdPtr;
778 }
779 tsdPtr->prevPtr = 0;
780 waitingListPtr = tsdPtr;
781 tsdPtr->onList = 1;
782
783 write(triggerPipe, "", 1);
784 }
785
786 FD_ZERO( &(tsdPtr->readyMasks.readable) );
787 FD_ZERO( &(tsdPtr->readyMasks.writable) );
788 FD_ZERO( &(tsdPtr->readyMasks.exceptional) );
789
790 if (!tsdPtr->eventReady) {
791 Tcl_ConditionWait(&tsdPtr->waitCV, &notifierMutex, timePtr);
792 }
793 tsdPtr->eventReady = 0;
794
795 if (waitForFiles && tsdPtr->onList) {
796 /*
797 * Remove the ThreadSpecificData structure of this thread from the
798 * waiting list. Alert the notifier thread to recompute its select
799 * masks - skipping this caused a hang when trying to close a pipe
800 * which the notifier thread was still doing a select on.
801 */
802
803 if (tsdPtr->prevPtr) {
804 tsdPtr->prevPtr->nextPtr = tsdPtr->nextPtr;
805 } else {
806 waitingListPtr = tsdPtr->nextPtr;
807 }
808 if (tsdPtr->nextPtr) {
809 tsdPtr->nextPtr->prevPtr = tsdPtr->prevPtr;
810 }
811 tsdPtr->nextPtr = tsdPtr->prevPtr = NULL;
812 tsdPtr->onList = 0;
813 write(triggerPipe, "", 1);
814 }
815
816
817 #else
818 tsdPtr->readyMasks = tsdPtr->checkMasks;
819 numFound = select( tsdPtr->numFdBits,
820 &(tsdPtr->readyMasks.readable),
821 &(tsdPtr->readyMasks.writable),
822 &(tsdPtr->readyMasks.exceptional),
823 timeoutPtr );
824
825 /*
826 * Some systems don't clear the masks after an error, so
827 * we have to do it here.
828 */
829
830 if (numFound == -1) {
831 FD_ZERO( &(tsdPtr->readyMasks.readable ) );
832 FD_ZERO( &(tsdPtr->readyMasks.writable ) );
833 FD_ZERO( &(tsdPtr->readyMasks.exceptional ) );
834 }
835
836 #ifdef _LANG
837 /*
838 * Language-specific check for signals
839 */
840 if (numFound == -1 && errno == EINTR) {
841 LangAsyncCheck();
842 }
843 #endif
844
845 #endif
846
847 /*
848 * Queue all detected file events before returning.
849 */
850
851 for (filePtr = tsdPtr->firstFileHandlerPtr; (filePtr != NULL);
852 filePtr = filePtr->nextPtr) {
853
854 mask = 0;
855 if ( FD_ISSET( filePtr->fd, &(tsdPtr->readyMasks.readable) ) ) {
856 mask |= TCL_READABLE;
857 }
858 if ( FD_ISSET( filePtr->fd, &(tsdPtr->readyMasks.writable) ) ) {
859 mask |= TCL_WRITABLE;
860 }
861 if ( FD_ISSET( filePtr->fd, &(tsdPtr->readyMasks.exceptional) ) ) {
862 mask |= TCL_EXCEPTION;
863 }
864
865 if (!mask) {
866 continue;
867 }
868
869 /*
870 * Don't bother to queue an event if the mask was previously
871 * non-zero since an event must still be on the queue.
872 */
873
874 if (filePtr->readyMask == 0) {
875 fileEvPtr = (FileHandlerEvent *) ckalloc(
876 sizeof(FileHandlerEvent));
877 fileEvPtr->header.proc = FileHandlerEventProc;
878 fileEvPtr->fd = filePtr->fd;
879 Tcl_QueueEvent((Tcl_Event *) fileEvPtr, TCL_QUEUE_TAIL);
880 }
881 filePtr->readyMask = mask;
882 }
883 #ifdef TCL_THREADS
884 Tcl_MutexUnlock(&notifierMutex);
885 #endif
886 return 0;
887 }
888
889 #ifdef TCL_THREADS
890 /*
891 *----------------------------------------------------------------------
892 *
893 * NotifierThreadProc --
894 *
895 * This routine is the initial (and only) function executed by the
896 * special notifier thread. Its job is to wait for file descriptors
897 * to become readable or writable or to have an exception condition
898 * and then to notify other threads who are interested in this
899 * information by signalling a condition variable. Other threads
900 * can signal this notifier thread of a change in their interests
901 * by writing a single byte to a special pipe that the notifier
902 * thread is monitoring.
903 *
904 * Result:
905 * None. Once started, this routine never exits. It dies with
906 * the overall process.
907 *
908 * Side effects:
909 * The trigger pipe used to signal the notifier thread is created
910 * when the notifier thread first starts.
911 *
912 *----------------------------------------------------------------------
913 */
914
915 static void
916 NotifierThreadProc(clientData)
917 ClientData clientData; /* Not used. */
918 {
919 ThreadSpecificData *tsdPtr;
920 fd_set readableMask;
921 fd_set writableMask;
922 fd_set exceptionalMask;
923 int fds[2];
924 int i, status, numFdBits, receivePipe;
925 long found;
926 struct timeval poll = {0., 0.}, *timePtr;
927 char buf[2];
928
929 if (pipe(fds) != 0) {
930 panic("NotifierThreadProc: could not create trigger pipe.");
931 }
932
933 receivePipe = fds[0];
934
935 #ifndef USE_FIONBIO
936 status = fcntl(receivePipe, F_GETFL);
937 status |= O_NONBLOCK;
938 if (fcntl(receivePipe, F_SETFL, status) < 0) {
939 panic("NotifierThreadProc: could not make receive pipe non blocking.");
940 }
941 status = fcntl(fds[1], F_GETFL);
942 status |= O_NONBLOCK;
943 if (fcntl(fds[1], F_SETFL, status) < 0) {
944 panic("NotifierThreadProc: could not make trigger pipe non blocking.");
945 }
946 #else
947 if (ioctl(receivePipe, (int) FIONBIO, &status) < 0) {
948 panic("NotifierThreadProc: could not make receive pipe non blocking.");
949 }
950 if (ioctl(fds[1], (int) FIONBIO, &status) < 0) {
951 panic("NotifierThreadProc: could not make trigger pipe non blocking.");
952 }
953 #endif
954
955 /*
956 * Install the write end of the pipe into the global variable.
957 */
958
959 Tcl_MutexLock(&notifierMutex);
960 triggerPipe = fds[1];
961
962 /*
963 * Signal any threads that are waiting.
964 */
965
966 Tcl_ConditionNotify(&notifierCV);
967 Tcl_MutexUnlock(&notifierMutex);
968
969 /*
970 * Look for file events and report them to interested threads.
971 */
972
973 while (1) {
974
975 FD_ZERO( &readableMask );
976 FD_ZERO( &writableMask );
977 FD_ZERO( &exceptionalMask );
978
979 /*
980 * Compute the logical OR of the select masks from all the
981 * waiting notifiers.
982 */
983
984 Tcl_MutexLock(&notifierMutex);
985 timePtr = NULL;
986 for (tsdPtr = waitingListPtr; tsdPtr; tsdPtr = tsdPtr->nextPtr) {
987 for ( i = tsdPtr->numFdBits-1; i >= 0; --i ) {
988 if ( FD_ISSET( i, &(tsdPtr->checkMasks.readable) ) ) {
989 FD_SET( i, &readableMask );
990 }
991 if ( FD_ISSET( i, &(tsdPtr->checkMasks.writable) ) ) {
992 FD_SET( i, &writableMask );
993 }
994 if ( FD_ISSET( i, &(tsdPtr->checkMasks.exceptional) ) ) {
995 FD_SET( i, &exceptionalMask );
996 }
997 }
998 if ( tsdPtr->numFdBits > numFdBits ) {
999 numFdBits = tsdPtr->numFdBits;
1000 }
1001 if (tsdPtr->pollState & POLL_WANT) {
1002 /*
1003 * Here we make sure we go through select() with the same
1004 * mask bits that were present when the thread tried to poll.
1005 */
1006
1007 tsdPtr->pollState |= POLL_DONE;
1008 timePtr = &poll;
1009 }
1010 }
1011 Tcl_MutexUnlock(&notifierMutex);
1012
1013 /*
1014 * Set up the select mask to include the receive pipe.
1015 */
1016
1017 if ( receivePipe >= numFdBits ) {
1018 numFdBits = receivePipe + 1;
1019 }
1020 FD_SET( receivePipe, &readableMask );
1021
1022 if ( select( numFdBits, &readableMask, &writableMask,
1023 &exceptionalMask, timePtr) == -1 ) {
1024 /*
1025 * Try again immediately on an error.
1026 */
1027
1028 continue;
1029 }
1030
1031 /*
1032 * Alert any threads that are waiting on a ready file descriptor.
1033 */
1034
1035 Tcl_MutexLock(&notifierMutex);
1036 for (tsdPtr = waitingListPtr; tsdPtr; tsdPtr = tsdPtr->nextPtr) {
1037 found = 0;
1038
1039 for ( i = tsdPtr->numFdBits-1; i >= 0; --i ) {
1040 if ( FD_ISSET( i, &(tsdPtr->checkMasks.readable) )
1041 && FD_ISSET( i, &readableMask ) ) {
1042 FD_SET( i, &(tsdPtr->readyMasks.readable) );
1043 found = 1;
1044 }
1045 if ( FD_ISSET( i, &(tsdPtr->checkMasks.writable) )
1046 && FD_ISSET( i, &writableMask ) ) {
1047 FD_SET( i, &(tsdPtr->readyMasks.writable) );
1048 found = 1;
1049 }
1050 if ( FD_ISSET( i, &(tsdPtr->checkMasks.exceptional) )
1051 && FD_ISSET( i, &exceptionalMask ) ) {
1052 FD_SET( i, &(tsdPtr->readyMasks.exceptional) );
1053 found = 1;
1054 }
1055 }
1056
1057 if (found || (tsdPtr->pollState & POLL_DONE)) {
1058 tsdPtr->eventReady = 1;
1059 if (tsdPtr->onList) {
1060 /*
1061 * Remove the ThreadSpecificData structure of this
1062 * thread from the waiting list. This prevents us from
1063 * continuously spining on select until the other
1064 * threads runs and services the file event.
1065 */
1066
1067 if (tsdPtr->prevPtr) {
1068 tsdPtr->prevPtr->nextPtr = tsdPtr->nextPtr;
1069 } else {
1070 waitingListPtr = tsdPtr->nextPtr;
1071 }
1072 if (tsdPtr->nextPtr) {
1073 tsdPtr->nextPtr->prevPtr = tsdPtr->prevPtr;
1074 }
1075 tsdPtr->nextPtr = tsdPtr->prevPtr = NULL;
1076 tsdPtr->onList = 0;
1077 tsdPtr->pollState = 0;
1078 }
1079 Tcl_ConditionNotify(&tsdPtr->waitCV);
1080 }
1081 }
1082 Tcl_MutexUnlock(&notifierMutex);
1083
1084 /*
1085 * Consume the next byte from the notifier pipe if the pipe was
1086 * readable. Note that there may be multiple bytes pending, but
1087 * to avoid a race condition we only read one at a time.
1088 */
1089
1090 if ( FD_ISSET( receivePipe, &readableMask ) ) {
1091 i = read(receivePipe, buf, 1);
1092
1093 if ((i == 0) || ((i == 1) && (buf[0] == 'q'))) {
1094 /*
1095 * Someone closed the write end of the pipe or sent us a
1096 * Quit message [Bug: 4139] and then closed the write end
1097 * of the pipe so we need to shut down the notifier thread.
1098 */
1099
1100 break;
1101 }
1102 }
1103 }
1104
1105 /*
1106 * Clean up the read end of the pipe and signal any threads waiting on
1107 * termination of the notifier thread.
1108 */
1109
1110 close(receivePipe);
1111 Tcl_MutexLock(&notifierMutex);
1112 triggerPipe = -1;
1113 Tcl_ConditionNotify(&notifierCV);
1114 Tcl_MutexUnlock(&notifierMutex);
1115 }
1116 #endif
1117 #endif
1118
1119