2 # Copyright 2016,2020 Ian Jackson
3 # SPDX-License-Identifier: GPL-3.0-or-later
4 # There is NO WARRANTY.
8 namespace eval subproc {
10 #----- general purpose subprocess handling -----
12 # One useful procedure:
13 # subprocess::fork ONDEATH INCHILD
14 # forks, evaluates INCHILD in the calling context but in the child
15 # and when the child dies evaluates [concat [list ONDEATH] W2 W3]
16 # where W2 and W3 are the 2nd and 3rd elements of the list returned
19 # INCHILD should not return; if it does or if it gets an error, the
20 # result is that the child gets a SIGKILL.
24 proc fork {ondeath inchild} {
26 global errorCode errorInfo
27 foreach f {stdout stderr} {
28 if {[catch { flush $f } emsg]} {
29 catch { bgerror $emsg }
37 puts stderr "CHILD ERROR $emsg\n$errorCode\n$errorInfo\n"
39 kill KILL [id process]
41 set children($pid) $ondeath
45 proc chld-handler {} {
48 if {[catch { set got [wait -nohang] }]} break
49 if {![llength $got]} break
50 manyset $got pid how how2
51 if {[info exists children($pid)]} {
55 uplevel #0 [concat [list $l] $how $how2]
57 catch { bgerror $emsg }
63 signal -restart trap CHLD { after idle subproc::chld-handler }