From 34eedcb52f02f4dddccace2f0d411bc8bc396150 Mon Sep 17 00:00:00 2001 From: Omar Rizwan Date: Sat, 17 Jun 2023 12:41:36 -0400 Subject: fork play --- play/fork-play.tcl | 23 ++++++++++++++++++++ play/zygote-play.tcl | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 play/fork-play.tcl create mode 100644 play/zygote-play.tcl diff --git a/play/fork-play.tcl b/play/fork-play.tcl new file mode 100644 index 00000000..920a8987 --- /dev/null +++ b/play/fork-play.tcl @@ -0,0 +1,23 @@ +source "lib/c.tcl" +set cc [c create] +$cc include +$cc proc ::fork {} int { + return fork(); +} +$cc compile + +puts "In parent ([pid]). Forking" +set pid [fork] +if {$pid == 0} { + puts "In child ([pid]). Forking" + set pid2 [fork] + if {$pid2 == 0} { + puts "In grandchild ([pid]). Done" + exit 0 + } + puts "In child. Done" + exit 0 +} + +puts "In parent. Done" +while true {} diff --git a/play/zygote-play.tcl b/play/zygote-play.tcl new file mode 100644 index 00000000..358e59cd --- /dev/null +++ b/play/zygote-play.tcl @@ -0,0 +1,60 @@ +source "lib/c.tcl" +set cc [c create] +$cc include +$cc proc ::fork {} int { + return fork(); +} +$cc compile + +namespace eval Zygote { + proc init {} { + variable writer + lassign [chan pipe] reader writer + set pid [fork] + if {$pid == 0} { + # We're in the child (the zygote). We will block waiting + # for commands from the parent (the original/main thread). + close $writer + + fconfigure $reader -buffering line + # Zygote's main loop: + set script "" + while {[gets $reader line] != -1} { + append script $line\n + if {[info complete $script]} { + # FIXME: This fork breaks it. + set pid [fork] + if {$pid == 0} { + eval $script + exit 0 + } + set script "" + } + } + exit 0 + + } else { + # We're still in the parent. The child (the zygote) is $pid. + close $reader + # We will send the zygote a message every time we want it to + # fork. + fconfigure $writer -buffering line + } + } + proc spawn {code} { + variable writer + puts $writer $code + } +} + +Zygote::init + +Zygote::spawn { + puts "hello from [pid]" +} +Zygote::spawn { + puts "wow from [pid]" +} + +after 3000 { puts done; set ::done true } +vwait ::done -- cgit v1.2.3