+## Collect a file descriptor for the controlling terminal. It's totally not
+## a problem if this doesn't work: then we'll just live without the job
+## control stuff, which is fine because we only need it when terminals are
+## involved.
+$TTYFD = POSIX::open "/dev/tty", O_RDWR;
+
+sub maybe_foreground_client () {
+ ## If we're currently the foreground process group, then make the client be
+ ## the foreground instead.
+
+ if (defined $TTYFD && $MYPGID == tcgetpgrp $TTYFD) {
+ kill -CONT, $CLIENTKID
+ or sysfail "failed to wake client: $!";
+ tcsetpgrp $TTYFD, $CLIENTKID
+ or sysfail "failed to make client the foreground process group: $!";
+ }
+}
+
+sub maybe_stop_self () {
+ ## If the client is currently the foreground process group, then we should
+ ## background ourselves.
+
+ if (defined $TTYFD && $CLIENTKID == tcgetpgrp $TTYFD) {
+ kill -TSTP, $MYPGID
+ or sysfail "failed to suspend own process group: $!";
+ }
+}
+
+set_sighandler "CONT", sub {
+ maybe_foreground_client;
+};
+
+set_sighandler "CHLD", sub {