1 /* sigproc.cc: inter/intra signal and sub process handler
3 Copyright 1997, 1998, 1999, 2000, 2001, 2002, 2003 Red Hat, Inc.
5 Written by Christopher Faylor
7 This file is part of Cygwin.
9 This software is a copyrighted work licensed under the terms of the
10 Cygwin license. Please consult the file "CYGWIN_LICENSE" for
18 #include <sys/cygwin.h>
20 #include <sys/signal.h>
29 #include "child_info_magic.h"
30 #include "shared_info.h"
31 #include "cygthread.h"
34 #include "perthread.h"
39 #define WSSC 60000 // Wait for signal completion
40 #define WPSP 40000 // Wait for proc_subproc mutex
42 #define PSIZE 63 // Number of processes
44 #define wake_wait_subproc() SetEvent (events[0])
46 #define no_signals_available() (!hwait_sig || !sig_loop_wait || exit_state)
56 friend class pending_signals;
57 friend int __stdcall sig_dispatch_pending ();
62 sigelem sigs[NSIG + 1];
69 void reset () {curr = &start; prev = &start;}
70 void add (int sig, int pid, _threadinfo *tls);
73 friend int __stdcall sig_dispatch_pending ();
85 static pending_signals sigqueue;
87 struct sigaction *global_sigs;
92 cygheap->sigs = global_sigs =
93 (struct sigaction *) ccalloc (HEAP_SIGS, NSIG, sizeof (struct sigaction));
97 signal_fixup_after_exec ()
99 global_sigs = cygheap->sigs;
100 /* Set up child's signal handlers */
101 for (int i = 0; i < NSIG; i++)
103 global_sigs[i].sa_mask = 0;
104 if (global_sigs[i].sa_handler != SIG_IGN)
105 global_sigs[i].sa_handler = SIG_DFL;
112 const char *__sp_fn ;
115 char NO_COPY myself_nowait_dummy[1] = {'0'};// Flag to sig_send that signal goes to
116 // current process but no wait is required
117 HANDLE NO_COPY signal_arrived; // Event signaled when a signal has
118 // resulted in a user-specified
125 /* How long to wait for message/signals. Normally this is infinite.
126 * On termination, however, these are set to zero as a flag to exit.
129 #define Static static NO_COPY
131 Static DWORD proc_loop_wait = 1000; // Wait for subprocesses to exit
132 Static DWORD sig_loop_wait = INFINITE; // Wait for signals to arrive
134 Static HANDLE sigcomplete_main; // Event signaled when a signal has
135 // finished processing for the main
137 HANDLE NO_COPY sigCONT; // Used to "STOP" a process
138 Static cygthread *hwait_sig; // Handle of wait_sig thread
139 Static cygthread *hwait_subproc; // Handle of sig_subproc thread
141 Static HANDLE wait_sig_inited; // Control synchronization of
142 // message queue startup
144 /* Used by WaitForMultipleObjects. These are handles to child processes.
146 Static HANDLE events[PSIZE + 1]; // All my children's handles++
147 #define hchildren (events + 1) // Where the children handles begin
148 Static char cpchildren[PSIZE * sizeof (pinfo)]; // All my children info
149 Static int nchildren; // Number of active children
150 Static char czombies[(NZOMBIES + 1) * sizeof (pinfo)]; // All my deceased children info
151 Static int nzombies; // Number of deceased children
153 #define pchildren ((pinfo *) cpchildren)
154 #define zombies ((pinfo *) czombies)
156 Static waitq waitq_head = {0, 0, 0, 0, 0, 0, 0};// Start of queue for wait'ing threads
157 Static waitq waitq_main; // Storage for main thread
159 muto NO_COPY *sync_proc_subproc = NULL; // Control access to subproc stuff
161 DWORD NO_COPY sigtid = 0; // ID of the signal thread
165 static int __stdcall checkstate (waitq *) __attribute__ ((regparm (1)));
166 static __inline__ BOOL get_proc_lock (DWORD, DWORD);
167 static void __stdcall remove_zombie (int);
168 static DWORD WINAPI wait_sig (VOID *arg);
169 static int __stdcall stopped_or_terminated (waitq *, _pinfo *);
170 static DWORD WINAPI wait_subproc (VOID *);
172 /* Determine if the parent process is alive.
176 my_parent_is_alive ()
179 if (!myself->ppid_handle)
181 debug_printf ("No myself->ppid_handle");
185 for (int i = 0; i < 2; i++)
186 switch (res = WaitForSingleObject (myself->ppid_handle, 0))
189 debug_printf ("parent dead.");
193 debug_printf ("parent still alive");
197 DWORD werr = GetLastError ();
198 if (werr == ERROR_INVALID_HANDLE && i == 0)
200 system_printf ("WFSO for myself->ppid_handle(%p) failed, error %d",
201 myself->ppid_handle, werr);
210 wait_for_sigthread ()
212 sigproc_printf ("wait_sig_inited %p", wait_sig_inited);
213 HANDLE hsig_inited = wait_sig_inited;
214 (void) WaitForSingleObject (hsig_inited, INFINITE);
215 wait_sig_inited = NULL;
216 (void) ForceCloseHandle1 (hsig_inited, wait_sig_inited);
219 /* Get the sync_proc_subproc muto to control access to
220 * children, zombie arrays.
221 * Attempt to handle case where process is exiting as we try to grab
225 get_proc_lock (DWORD what, DWORD val)
227 Static int lastwhat = -1;
228 if (!sync_proc_subproc)
230 if (sync_proc_subproc->acquire (WPSP))
235 if (!sync_proc_subproc)
237 system_printf ("Couldn't aquire sync_proc_subproc for(%d,%d), %E, last %d",
238 what, val, lastwhat);
242 static BOOL __stdcall
243 proc_can_be_signalled (_pinfo *p)
245 if (p == myself_nowait || p == myself)
247 assert (!wait_sig_inited);
251 return ISSTATE (p, PID_INITIALIZING) ||
252 (((p)->process_state & (PID_ACTIVE | PID_IN_USE)) ==
253 (PID_ACTIVE | PID_IN_USE));
257 pid_exists (pid_t pid)
260 return proc_exists (p);
263 /* Test to determine if a process really exists and is processing signals.
266 proc_exists (_pinfo *p)
268 return p && !(p->process_state & (PID_EXITED | PID_ZOMBIE));
271 /* Return 1 if this is one of our children, zero otherwise.
272 FIXME: This really should be integrated with the rest of the proc_subproc
273 testing. Scanning these lists twice is inefficient. */
277 for (int i = 0; i < nchildren; i++)
278 if (pchildren[i]->pid == pid)
280 for (int i = 0; i < nzombies; i++)
281 if (zombies[i]->pid == pid)
286 /* Handle all subprocess requests
288 #define vchild (*((pinfo *) val))
290 proc_subproc (DWORD what, DWORD val)
298 #define wval ((waitq *) val)
300 sigproc_printf ("args: %x, %d", what, val);
302 if (!get_proc_lock (what, val)) // Serialize access to this function
304 system_printf ("couldn't get proc lock. Something is wrong.");
310 /* Add a new subprocess to the children arrays.
311 * (usually called from the main thread)
314 if (nchildren >= PSIZE - 1)
319 pchildren[nchildren] = vchild;
320 hchildren[nchildren] = vchild->hProcess;
321 if (!DuplicateHandle (hMainProc, vchild->hProcess, hMainProc, &vchild->pid_handle,
322 0, 0, DUPLICATE_SAME_ACCESS))
323 system_printf ("Couldn't duplicate child handle for pid %d, %E", vchild->pid);
324 ProtectHandle1 (vchild->pid_handle, pid_handle);
326 if (!DuplicateHandle (hMainProc, hMainProc, vchild->hProcess, &vchild->ppid_handle,
327 SYNCHRONIZE | PROCESS_DUP_HANDLE, TRUE, 0))
328 system_printf ("Couldn't duplicate my handle<%p> for pid %d, %E", hMainProc, vchild->pid);
329 vchild->ppid = myself->pid;
330 vchild->uid = myself->uid;
331 vchild->gid = myself->gid;
332 vchild->pgid = myself->pgid;
333 vchild->sid = myself->sid;
334 vchild->ctty = myself->ctty;
335 vchild->process_state |= PID_INITIALIZING | (myself->process_state & PID_USETTY);
337 sigproc_printf ("added pid %d to wait list, slot %d, winpid %p, handle %p",
338 vchild->pid, nchildren, vchild->dwProcessId,
342 wake_wait_subproc ();
345 /* A child process had terminated.
346 Possibly this is just due to an exec(). Cygwin implements an exec()
347 as a "handoff" from one windows process to another. If child->hProcess
348 is different from what is recorded in hchildren, then this is an exec().
349 Otherwise this is a normal child termination event.
350 (called from wait_subproc thread) */
351 case PROC_CHILDTERMINATED:
352 if (hchildren[val] != pchildren[val]->hProcess)
354 sigproc_printf ("pid %d[%d], reparented old hProcess %p, new %p",
355 pchildren[val]->pid, val, hchildren[val], pchildren[val]->hProcess);
356 HANDLE h = hchildren[val];
357 hchildren[val] = pchildren[val]->hProcess; /* Filled out by child */
358 sync_proc_subproc->release (); // Release the lock ASAP
359 ForceCloseHandle1 (h, childhProc);
360 ProtectHandle1 (pchildren[val]->hProcess, childhProc);
362 goto out; // This was an exec()
365 sigproc_printf ("pid %d[%d] terminated, handle %p, nchildren %d, nzombies %d",
366 pchildren[val]->pid, val, hchildren[val], nchildren, nzombies);
369 thiszombie = nzombies;
370 zombies[nzombies] = pchildren[val]; // Add to zombie array
371 zombies[nzombies++]->process_state = PID_ZOMBIE;// Walking dead
373 sigproc_printf ("zombifying [%d], pid %d, handle %p, nchildren %d",
374 val, pchildren[val]->pid, hchildren[val], nchildren);
375 if ((int) val < --nchildren)
377 hchildren[val] = hchildren[nchildren];
378 pchildren[val] = pchildren[nchildren];
381 /* See if we should care about the this terminated process. If we've
382 filled up our table or if we're ignoring SIGCHLD, then we immediately
383 remove the process and move on. Otherwise, this process becomes a zombie
384 which must be reaped by a wait() call. */
385 if (nzombies >= NZOMBIES
386 || global_sigs[SIGCHLD].sa_handler == (void *) SIG_IGN)
388 sigproc_printf ("automatically removing zombie %d", thiszombie);
389 remove_zombie (thiszombie);
392 /* Don't scan the wait queue yet. Caller will send SIGCHLD to this process.
393 This will cause an eventual scan of waiters. */
396 /* Handle a wait4() operation. Allocates an event for the calling
397 * thread which is signaled when the appropriate pid exits or stops.
398 * (usually called from the main thread)
401 wval->ev = NULL; // Don't know event flag yet
404 child = NULL; // Not looking for a specific pid
405 else if (!mychild (wval->pid))
406 goto out; // invalid pid. flag no such child
408 wval->status = 0; // Don't know status yet
409 sigproc_printf ("wval->pid %d, wval->options %d", wval->pid, wval->options);
411 /* If the first time for this thread, create a new event, otherwise
414 if ((wval->ev = wval->thread_ev) == NULL)
416 wval->ev = wval->thread_ev = CreateEvent (&sec_none_nih, TRUE,
418 ProtectHandle (wval->ev);
421 ResetEvent (wval->ev);
423 waitq_head.next = wval; /* Add at the beginning. */
424 wval->next = w; /* Link in rest of the list. */
428 /* Clear all waiting threads. Called from exceptions.cc prior to
429 the main thread's dispatch to a signal handler function.
430 (called from wait_sig thread) */
432 /* Clear all "wait"ing threads. */
434 sigproc_printf ("clear waiting threads");
436 sigproc_printf ("looking for processes to reap");
440 /* Scan the linked list of wait()ing threads. If a wait's parameters
441 * match this pid, then activate it.
443 for (w = &waitq_head; w->next != NULL; w = w->next)
445 if ((potential_match = checkstate (w)) > 0)
446 sigproc_printf ("released waiting thread");
447 else if (!clearing && !(w->next->options & WNOHANG) && potential_match < 0)
448 sigproc_printf ("only found non-terminated children");
449 else if (potential_match <= 0) // nothing matched
451 sigproc_printf ("waiting thread found no children");
452 HANDLE oldw = w->next->ev;
455 w->next->status = -1; /* flag that a signal was received */
456 else if (!potential_match || !(w->next->options & WNOHANG))
458 if (!SetEvent (oldw))
459 system_printf ("couldn't wake up wait event %p, %E", oldw);
460 w->next = w->next->next;
467 sigproc_printf ("finished processing terminated/stopped child");
470 waitq_head.next = NULL;
471 sigproc_printf ("finished clearing");
477 sync_proc_subproc->release (); // Release the lock
479 sigproc_printf ("returning %d", rc);
483 /* Terminate the wait_subproc thread.
484 * Called on process exit.
485 * Also called by spawn_guts to disassociate any subprocesses from this
486 * process. Subprocesses will then know to clean up after themselves and
487 * will not become zombies.
490 proc_terminate (void)
492 sigproc_printf ("nchildren %d, nzombies %d", nchildren, nzombies);
493 /* Signal processing is assumed to be blocked in this routine. */
496 proc_loop_wait = 0; // Tell wait_subproc thread to exit
497 sync_proc_subproc->acquire (WPSP);
498 wake_wait_subproc (); // Wake wait_subproc loop
499 hwait_subproc = NULL;
501 (void) proc_subproc (PROC_CLEARWAIT, 1);
503 /* Clean out zombie processes from the pid list. */
505 for (i = 0; i < nzombies; i++)
507 if (zombies[i]->hProcess)
509 ForceCloseHandle1 (zombies[i]->hProcess, childhProc);
510 ForceCloseHandle1 (zombies[i]->pid_handle, pid_handle);
512 zombies[i]->ppid = 1;
513 zombies[i]->process_state = PID_EXITED; /* CGF FIXME - still needed? */
514 zombies[i].release (); // FIXME: this breaks older gccs for some reason
517 /* Disassociate my subprocesses */
518 for (i = 0; i < nchildren; i++)
520 if (!pchildren[i]->hProcess)
521 sigproc_printf ("%d(%d) hProcess cleared already?", pchildren[i]->pid,
522 pchildren[i]->dwProcessId);
525 ForceCloseHandle1 (pchildren[i]->hProcess, childhProc);
526 sigproc_printf ("%d(%d) closed child handle", pchildren[i]->pid,
527 pchildren[i]->dwProcessId);
528 pchildren[i]->ppid = 1;
529 if (pchildren[i]->pgid == myself->pid)
530 pchildren[i]->process_state |= PID_ORPHANED;
532 pchildren[i].release ();
534 nchildren = nzombies = 0;
535 /* Just zero sync_proc_subproc as the delete below seems to cause
536 problems for older gccs. */
537 sync_proc_subproc = NULL;
539 sigproc_printf ("leaving");
542 /* Clear pending signal */
544 sig_clear (int target_sig)
546 if (GetCurrentThreadId () != sigtid)
547 sig_send (myself, -target_sig);
552 while ((q = sigqueue.next ()))
553 if (q->sig == target_sig)
563 sigpending (sigset_t *mask)
565 sigset_t outset = (sigset_t) sig_send (myself, __SIGPENDING);
566 if (outset == SIG_BAD_MASK)
572 /* Force the wait_sig thread to wake up and scan for pending signals */
574 sig_dispatch_pending ()
576 if (exit_state || GetCurrentThreadId () == sigtid || !sigqueue.start.next)
579 (void) sig_send (myself, __SIGFLUSH);
580 return call_signal_handler_now ();
583 /* Message initialization. Called from dll_crt0_1
585 * This routine starts the signal handling thread. The wait_sig_inited
586 * event is used to signal that the thread is ready to handle signals.
587 * We don't wait for this during initialization but instead detect it
588 * in sig_send to gain a little concurrency.
593 wait_sig_inited = CreateEvent (&sec_none_nih, TRUE, FALSE, NULL);
594 ProtectHandle (wait_sig_inited);
596 /* sync_proc_subproc is used by proc_subproc. It serialises
597 * access to the children and zombie arrays.
599 new_muto (sync_proc_subproc);
601 /* local event signaled when main thread has been dispatched
602 to a signal handler function. */
603 signal_arrived = CreateEvent (&sec_none_nih, TRUE, FALSE, NULL);
604 ProtectHandle (signal_arrived);
606 hwait_sig = new cygthread (wait_sig, cygself, "sig");
609 /* Initialize waitq structure for main thread. A waitq structure is
610 * allocated for each thread that executes a wait to allow multiple threads
611 * to perform waits. Pre-allocate a waitq structure for the main thread.
614 if ((w = (waitq *)waitq_storage.get ()) == NULL)
617 waitq_storage.set (w);
619 memset (w, 0, sizeof *w); // Just to be safe
621 global_sigs[SIGSTOP].sa_flags = SA_RESTART | SA_NODEFER;
622 sigproc_printf ("process/signal handling enabled(%x)", myself->process_state);
626 /* Called on process termination to terminate signal and process threads.
629 sigproc_terminate (void)
634 sigproc_printf ("sigproc handling not active");
637 sigproc_printf ("entering");
638 sig_loop_wait = 0; // Tell wait_sig to exit when it is
639 // finished with anything it is doing
640 ForceCloseHandle (sigcomplete_main);
641 CloseHandle (myself->sendsig);
643 proc_terminate (); // Terminate process handling thread
648 /* Send a signal to another process by raising its signal semaphore.
649 * If pinfo *p == NULL, send to the current process.
650 * If sending to this process, wait for notification that a signal has
651 * completed before returning.
654 sig_send (_pinfo *p, int sig, void *tls)
661 bool wait_for_completion;
662 // FIXMENOW: Avoid using main thread's completion event!
663 if (!(its_me = (p == NULL || p == myself || p == myself_nowait)))
664 wait_for_completion = false;
667 if (no_signals_available ())
668 goto out; // Either exiting or not yet initializing
670 wait_for_sigthread ();
671 wait_for_completion = p != myself_nowait && _my_tls.isinitialized ();
675 /* It is possible that the process is not yet ready to receive messages
676 * or that it has exited. Detect this.
678 if (!proc_can_be_signalled (p)) /* Is the process accepting messages? */
680 sigproc_printf ("invalid pid %d(%x), signal %d",
681 p->pid, p->process_state, sig);
686 sigproc_printf ("pid %d, signal %d, its_me %d", p->pid, sig, its_me);
690 sendsig = myself->sendsig;
691 if (wait_for_completion)
692 pack.wakeup = sigcomplete_main;
696 HANDLE hp = OpenProcess (PROCESS_DUP_HANDLE, false, p->dwProcessId);
699 sigproc_printf ("OpenProcess failed, %E");
703 for (int i = 0; !p->sendsig && i < 10000; i++)
704 low_priority_sleep (0);
705 if (!DuplicateHandle (hp, p->sendsig, hMainProc, &sendsig, false, 0,
706 DUPLICATE_SAME_ACCESS) || !sendsig)
708 sigproc_printf ("DuplicateHandle failed, %E");
719 else if (sig == __SIGPENDING)
720 pack.mask = &pending;
721 else if (sig == __SIGFLUSH || sig > 0)
722 pack.mask = &myself->getsigmask ();
727 pack.pid = myself->pid;
728 pack.tls = (_threadinfo *) tls;
730 if (!WriteFile (sendsig, &pack, sizeof (pack), &nb, NULL) || nb != sizeof (pack))
732 /* Couldn't send to the pipe. This probably means that the
733 process is exiting. */
736 sigproc_printf ("WriteFile for pipe %p failed, %E", sendsig);
738 ForceCloseHandle (sendsig);
742 if (no_signals_available ())
743 sigproc_printf ("I'm going away now");
745 system_printf ("error sending signal %d to pid %d, pipe handle %p, %E",
746 sig, p->pid, sendsig);
752 /* No need to wait for signal completion unless this was a signal to
755 If it was a signal to this process, wait for a dispatched signal.
756 Otherwise just wait for the wait_sig to signal that it has finished
757 processing the signal. */
758 if (wait_for_completion)
760 sigproc_printf ("Waiting for pack.wakeup %p", pack.wakeup);
761 rc = WaitForSingleObject (pack.wakeup, WSSC);
766 sigproc_printf ("Not waiting for sigcomplete. its_me %d signal %d", its_me, sig);
768 ForceCloseHandle (sendsig);
771 if (rc == WAIT_OBJECT_0)
772 rc = 0; // Successful exit
775 /* It's an error unless sig_loop_wait == 0 (the process is exiting). */
776 if (!no_signals_available ())
777 system_printf ("wait for sig_complete event failed, signal %d, rc %d, %E",
783 if (wait_for_completion)
784 call_signal_handler_now ();
787 if (sig != __SIGPENDING)
793 sigproc_printf ("returning %p from sending signal %d", rc, sig);
797 /* Initialize the wait_subproc thread.
798 * Called from fork() or spawn() to initialize the handling of subprocesses.
806 /* A "wakeup" handle which can be toggled to make wait_subproc reexamine
807 * the hchildren array.
809 events[0] = CreateEvent (&sec_none_nih, FALSE, FALSE, NULL);
810 hwait_subproc = new cygthread (wait_subproc, NULL, "proc");
811 hwait_subproc->zap_h ();
812 ProtectHandle (events[0]);
813 sigproc_printf ("started wait_subproc thread");
816 /* Initialize some of the memory block passed to child processes
817 by fork/spawn/exec. */
820 init_child_info (DWORD chtype, child_info *ch, pid_t pid, HANDLE subproc_ready)
822 memset (ch, 0, sizeof *ch);
823 ch->cb = chtype == PROC_FORK ? sizeof (child_info_fork) : sizeof (child_info);
824 ch->intro = PROC_MAGIC_GENERIC;
825 ch->magic = CHILD_INFO_MAGIC;
828 ch->subproc_ready = subproc_ready;
829 ch->pppid_handle = myself->ppid_handle;
830 ch->fhandler_union_cb = sizeof (fhandler_union);
831 ch->user_h = cygwin_user_h;
834 /* Check the state of all of our children to see if any are stopped or
838 checkstate (waitq *parent_w)
840 int potential_match = 0;
842 sigproc_printf ("nchildren %d, nzombies %d", nchildren, nzombies);
844 /* Check already dead processes first to see if they match the criteria
847 for (int i = 0; i < nzombies; i++)
848 switch (stopped_or_terminated (parent_w, zombies[i]))
851 potential_match = -1;
859 sigproc_printf ("checking alive children");
861 /* No dead terminated children matched. Check for stopped children. */
862 for (int i = 0; i < nchildren; i++)
863 switch (stopped_or_terminated (parent_w, pchildren[i]))
866 potential_match = -1;
874 sigproc_printf ("returning %d", potential_match);
875 return potential_match;
878 /* Remove a zombie from zombies by swapping it with the last child in the list.
880 static void __stdcall
881 remove_zombie (int ci)
883 sigproc_printf ("removing %d, pid %d, nzombies %d", ci, zombies[ci]->pid,
888 ForceCloseHandle1 (zombies[ci]->hProcess, childhProc);
889 ForceCloseHandle1 (zombies[ci]->pid_handle, pid_handle);
890 zombies[ci].release ();
894 zombies[ci] = zombies[nzombies];
899 /* Check status of child process vs. waitq member.
901 * parent_w is the pointer to the parent of the waitq member in question.
902 * child is the subprocess being considered.
905 * 1 if stopped or terminated child matches parent_w->next criteria
906 * -1 if a non-stopped/terminated child matches parent_w->next criteria
907 * 0 if child does not match parent_w->next criteria
910 stopped_or_terminated (waitq *parent_w, _pinfo *child)
913 waitq *w = parent_w->next;
915 sigproc_printf ("considering pid %d", child->pid);
918 else if (w->pid == 0)
919 potential_match = child->pgid == myself->pgid;
921 potential_match = child->pgid == -w->pid;
923 potential_match = (w->pid == child->pid);
925 if (!potential_match)
930 if ((terminated = child->process_state == PID_ZOMBIE) ||
931 ((w->options & WUNTRACED) && child->stopsig))
933 parent_w->next = w->next; /* successful wait. remove from wait queue */
938 sigproc_printf ("stopped child");
939 w->status = (child->stopsig << 8) | 0x7f;
942 else /* Should only get here when child has been moved to the zombies array */
945 if (!GetExitCodeProcess (child->hProcess, &status))
947 if (status & EXIT_SIGNAL)
948 w->status = (status >> 8) & 0xff; /* exited due to signal */
950 w->status = (status & 0xff) << 8; /* exited via "exit ()" */
952 add_rusage (&myself->rusage_children, &child->rusage_children);
953 add_rusage (&myself->rusage_children, &child->rusage_self);
957 add_rusage ((struct rusage *) w->rusage, &child->rusage_children);
958 add_rusage ((struct rusage *) w->rusage, &child->rusage_self);
962 if (!SetEvent (w->ev)) /* wake up wait4 () immediately */
963 system_printf ("couldn't wake up wait event %p, %E", w->ev);
967 return -potential_match;
973 winpids pids ((DWORD) PID_MAP_RW);
974 for (unsigned i = 0; i < pids.npids; i++)
975 if (pids[i]->hello_pid == myself->pid)
976 if (!IsBadWritePtr (pids[i], sizeof (_pinfo)))
977 pids[i]->commune_recv ();
980 /* Process signals by waiting for a semaphore to become signaled.
981 Then scan an in-memory array representing queued signals.
982 Executes in a separate thread.
984 Signals sent from this process are sent a completion signal so
985 that returns from kill/raise do not occur until the signal has
986 has been handled, as per POSIX. */
989 pending_signals::add (int sig, int pid, _threadinfo *tls)
992 for (se = start.next; se; se = se->next)
995 while (sigs[empty].sig)
1012 pending_signals::del ()
1014 sigelem *next = curr->next;
1022 empty = curr - sigs;
1027 pending_signals::next ()
1031 if (!curr || !(curr = curr->next))
1038 /* Process signals by waiting for signal data to arrive in a pipe.
1039 Set a completion event if one was specified. */
1041 wait_sig (VOID *self)
1046 /* Initialization */
1047 (void) SetThreadPriority (GetCurrentThread (), WAIT_SIG_PRIORITY);
1049 /* sigcomplete_main - event used to signal main thread on signal
1051 if (!CreatePipe (&readsig, &myself->sendsig, sec_user_nih (sa_buf), 0))
1052 api_fatal ("couldn't create signal pipe, %E");
1053 sigcomplete_main = CreateEvent (&sec_none_nih, FALSE, FALSE, NULL);
1054 sigproc_printf ("sigcomplete_main %p", sigcomplete_main);
1055 sigCONT = CreateEvent (&sec_none_nih, FALSE, FALSE, NULL);
1057 /* Setting dwProcessId flags that this process is now capable of receiving
1058 signals. Prior to this, dwProcessId was set to the windows pid of
1059 of the original windows process which spawned us unless this was a
1060 "toplevel" process. */
1061 myself->dwProcessId = GetCurrentProcessId ();
1062 myself->process_state |= PID_ACTIVE;
1063 myself->process_state &= ~PID_INITIALIZING;
1065 ProtectHandle (sigcomplete_main);
1067 /* If we've been execed, then there is still a stub left in the previous
1068 windows process waiting to see if it's started a cygwin process or not.
1069 Signalling subproc_ready indicates that we are a cygwin process. */
1070 if (child_proc_info && child_proc_info->type == PROC_EXEC)
1072 debug_printf ("subproc_ready %p", child_proc_info->subproc_ready);
1073 if (!SetEvent (child_proc_info->subproc_ready))
1074 system_printf ("SetEvent (subproc_ready) failed, %E");
1075 ForceCloseHandle1 (child_proc_info->subproc_ready, subproc_ready);
1076 /* Initialize an "indirect" pid block so that if someone looks up this
1077 process via its Windows PID it will be redirected to the appropriate
1078 Cygwin PID shared memory block. */
1079 static pinfo NO_COPY myself_identity;
1080 myself_identity.init (cygwin_pid (myself->dwProcessId), PID_EXECED);
1083 SetEvent (wait_sig_inited);
1084 sigtid = GetCurrentThreadId ();
1090 if (!ReadFile (readsig, &pack, sizeof (pack), &nb, NULL))
1093 if (nb != sizeof (pack))
1095 system_printf ("short read from signal pipe: %d != %d", nb,
1103 system_printf ("zero signal?");
1108 sigset_t dummy_mask;
1111 dummy_mask = myself->getsigmask ();
1112 pack.mask = &dummy_mask;
1128 while ((q = sigqueue.next ()))
1129 if (myself->getsigmask () & (bit = SIGTOMASK (q->sig)))
1134 while ((q = sigqueue.next ()))
1135 if (sig_handle (q->sig, *pack.mask, q->pid, q->tls) > 0)
1140 sig_clear (-pack.sig);
1143 if (sig_handle (pack.sig, *pack.mask, pack.pid, pack.tls) <= 0)
1144 sigqueue.add (pack.sig, pack.pid, pack.tls);// FIXME: Shouldn't add this in !sh condition
1145 if (pack.sig == SIGCHLD)
1146 proc_subproc (PROC_CLEARWAIT, 0);
1151 SetEvent (pack.wakeup);
1154 sigproc_printf ("done");
1158 /* Wait for subprocesses to terminate. Executes in a separate thread. */
1160 wait_subproc (VOID *)
1162 sigproc_printf ("starting");
1167 DWORD rc = WaitForMultipleObjects (nchildren + 1, events, FALSE,
1169 if (rc == WAIT_TIMEOUT)
1170 if (!proc_loop_wait)
1175 if (rc == WAIT_FAILED)
1177 if (!proc_loop_wait)
1180 /* It's ok to get an ERROR_INVALID_HANDLE since another thread may have
1181 closed a handle in the children[] array. So, we try looping a couple
1182 of times to stabilize. FIXME - this is not foolproof. Probably, this
1183 thread should be responsible for closing the children. */
1185 proc_subproc (PROC_NOTHING, 0); // Just synchronize and continue
1189 system_printf ("wait failed. nchildren %d, wait %d, %E",
1190 nchildren, proc_loop_wait);
1192 for (int i = 0; i <= nchildren; i++)
1193 if ((rc = WaitForSingleObject (events[i], 0)) == WAIT_OBJECT_0 ||
1197 system_printf ("nchildren %d, event[%d] %p, %E", nchildren, i, events[i]);
1200 system_printf ("nchildren %d, event[%d] %p, pchildren[%d] %p, events[0] %p, %E",
1201 nchildren, i, events[i], i - 1, (_pinfo *) pchildren[i - 1], events[0]);
1202 system_printf ("pid %d, dwProcessId %u, hProcess %p, progname '%s'",
1203 pchildren[i - 1]->pid, pchildren[i - 1]->dwProcessId,
1204 pchildren[i - 1]->hProcess, pchildren[i - 1]->progname);
1210 rc -= WAIT_OBJECT_0;
1213 rc = proc_subproc (PROC_CHILDTERMINATED, rc);
1214 if (!proc_loop_wait) // Don't bother if wait_subproc is
1217 /* Send a SIGCHLD to myself. We do this here, rather than in proc_subproc
1218 to avoid the proc_subproc lock since the signal thread will eventually
1219 be calling proc_subproc and could unnecessarily block. */
1221 sig_send (myself_nowait, SIGCHLD);
1223 sigproc_printf ("looping");
1226 ForceCloseHandle (events[0]);
1228 sigproc_printf ("done");