←  cshw: The C Shell for Windows

Chapter 13

Job Control

In This Chapter

Welcome to Part IV. The first eleven chapters got you fluent at the shell as a productivity tool — commands, files, scripts, control flow, data. The next six chapters cover what makes cshw a platform — features that let your shell run many things at once, talk to the network, call AI providers, and load your own compiled extensions.

This chapter opens with the simplest of those: job control. The ability to start a long-running command, set it aside in the background, do other work while it runs, and bring it back when you want it.

If you're coming from Unix or macOS, the commands here will look familiar — jobs, bg, fg, kill, the & suffix. That's deliberate; cshw inherits the csh job-control vocabulary directly. If you're coming from cmd.exe, this is mostly new. cmd.exe doesn't have job control in any meaningful sense — there's start for launching detached processes, and that's about it. PowerShell has Start-Job / Get-Job / Stop-Job, but the interaction model is bulkier than what you'll see here.


Why Job Control?

You're working on something — editing a file, looking at output, typing the next command — when you remember you need to kick off a long-running build, or compress a large folder, or run a one-hour data import. Without job control, you start the command and you're stuck staring at it until it finishes. The shell is busy; you wait.

Job control flips that around. Start the long-running thing in the background, and the prompt comes right back. You can keep working. Periodically check on the job, bring it forward if it needs attention, terminate it if something went wrong, or just let it finish in its own time.

Multiple jobs can run at once — three slow downloads, a compile, and a script — all sharing the shell, all listed by jobs, all manageable through the small command vocabulary we're about to cover.


Launching in the Background: The & Suffix

The simplest way to start a job in the background is to add & to the end of the command line:

longprocess.exe &

The command launches; the shell immediately prints a job number and process ID and returns to the prompt:

[1] 12384
CSHW C:\Users\You > 

[1] is the job number (a small integer cshw assigns; the first job is 1, the second is 2, and so on). 12384 is the system PID — Windows' identifier for the process. You'll use the job number with most cshw commands and the PID with system-level tools like Task Manager.

The job runs in parallel with whatever you do next. You can fire off three backups in a row:

backup-photos.cshw &
backup-docs.cshw &
backup-code.cshw &

All three run concurrently. The shell's still available for whatever else.

WARNING

A backgrounded command's output (anything it would have printed to your terminal) keeps writing to your terminal, mixed in with whatever you're typing. For background jobs that produce visible output, redirect with > log.txt so the output goes to a file instead. Example: longprocess > out.log 2>&1 & runs the process in the background with stdout and stderr captured in out.log, keeping your prompt clean.


What's Running: jobs

To see everything you've started:

jobs

Output looks like this:

JobID  PID          State      Command
------ ------------ ---------- --------------------------------
1      12384        Running    longprocess.exe
2      12388        Stopped    editor.exe
3      12392        Running    backup.cshw

Each row tells you the job number, the process ID, the state, and the command line that started it.

Job states

The state column tells you what each job is doing:

A completed job stays in the jobs list long enough for one jobs invocation to see it, then drops off — so if you jobs immediately after a job ends, you'll see it; if you jobs two seconds later, it's gone.

Options

A few common flags:

jobs -l          # long format -- includes PIDs
jobs -p          # only PIDs (one per line, useful for piping to kill)
jobs -r          # only running jobs
jobs -s          # only stopped jobs

A foreach loop over jobs -p is the cshw way to nuke everything when you've started a bunch of background jobs and want them all gone:

foreach pid (`jobs -p`)
    kill $pid
end

TIP

Run jobs periodically while you have background work going. Each row is "still running" or "done" — at a glance you know whether to wait or move on. Most experienced users jobs reflexively every few minutes.


Suspending: Ctrl+Z and stop

If you have a foreground command running and you want to pause it without losing the work it's done — maybe you started it without & and now you wish you had — you can suspend it.

Ctrl+Z (the keyboard shortcut)

While a foreground command is running, press Ctrl+Z. The shell suspends the running process and gives you the prompt back:

slow_command.exe
... working ...
^Z
[1]+ Stopped     slow_command.exe
CSHW C:\Users\You > 

The process is paused, not killed. Its memory is intact, its state is preserved, and you can resume it later with fg or bg (next section).

The stop command

For jobs that are already in the background, use stop with a job number:

stop 1                    # suspend job 1
stop 3                    # suspend job 3

Or stop a system process by its PID:

stop 12384

Why suspend a background job? Mostly to free up CPU temporarily — if you started a build in the background and now you need full CPU for something else, stop pauses the build until you bg it again.

REMEMBER

Suspended is not the same as killed. A suspended process holds its memory and its open files; resume it and it picks up where it left off. A killed process is gone — its memory is freed, its work is lost.


Moving Things Around: bg and fg

Once you have a suspended job, you have two choices: keep it suspended (rare), put it in the background (bg), or pull it to the foreground (fg).

bg — to the background

bg              # resume the most recently suspended job in the background
bg 2            # resume job 2 in the background

bg takes a job number and resumes that job. The job is now running in the background, just as if you'd started it with &.

The classic workflow:

build.cshw                    # started in foreground, takes forever
^Z                            # press Ctrl+Z to suspend
                              # [1]+ Stopped  build.cshw
bg                            # resume in background
                              # [1]+ build.cshw &
                              # prompt is back, build runs on

That's the "oops I forgot the &" recovery — three keystrokes from "stuck staring at this command" to "still running, but in the background."

fg — to the foreground

fg 1            # bring job 1 to the foreground
fg 2            # bring job 2 to the foreground

fg pulls a job back to interactive use. The shell waits for it to finish, exactly as if you'd started it without & in the first place. While the job is in the foreground, you can interact with it (type input, watch output) and Ctrl+Z works again to suspend it.

A common pattern: start a long compile in the background, do other work, then fg it when you want to watch the final stages of the build.

TRY IT

Open cshw and run:

sleep 30 &
jobs

You should see job 1, running, with sleep 30 as the command. Now fg 1 and watch the shell wait for sleep to finish (you can Ctrl+C if you don't want to wait the full 30 seconds). Practice with bg, fg, and Ctrl+Z until the dance feels natural.


Terminating: kill

Suspending a job is reversible. Killing it isn't.

kill 12384                # by PID -- terminate gracefully
kill 1                    # by job number -- same

cshw accepts either: a process ID (any positive integer), or a job number from the local jobs list (just the number; the % prefix that Unix uses is optional). Use job numbers for your own background jobs; use PIDs when you found the target via processlist (next section) and don't have a local job for it.

Graceful vs. forced — and signal selection

By default, kill sends a request to the process to terminate — the process gets a chance to clean up (close files, flush buffers). Most well-behaved programs respect this and exit cleanly.

For programs that ignore the request (hung, frozen, or just stubborn), use -9 to force termination:

kill -9 12384             # terminate immediately, no cleanup
kill -9 3                 # same, by job number

The -9 is the venerable "you have no choice in this matter" form. The process gets no time to clean up; Windows kills it dead. Use sparingly — if the process was in the middle of writing a file, that file may be corrupt afterward.

kill also accepts arbitrary integer signals (-1, -2, -15, -20) and the standard symbolic names (-TERM, -HUP, -INT, -KILL), the same vocabulary you'd use on Linux. cshw maps each one to the closest Windows equivalent — -TERM/-15 requests a graceful shutdown (with a Ctrl+C fallback for console-only processes that don't have a message loop), -KILL/-9 forces termination, -INT/-2 sends a Ctrl+C, and so on. Scripts ported from bash that say kill -HUP $pid work without translation.

Process trees

For processes that have spawned children of their own (a script that started a sub-script that started a tool), use /t to terminate the whole tree at once:

kill /t 12384             # kill 12384 and all its descendants
kill /f /t 12384          # force-kill the whole tree

Without /t, you'd kill the parent and leave the children running as orphans. /t is the right move for "make this whole thing stop, including everything it spawned."

TIP

A clean shutdown order: try kill PID first. Wait a couple of seconds. If the process is still there (visible in processlist), escalate to kill -9 PID. Most processes respond to the polite form; only the hung ones need the hammer.


Surviving Shell Exit: nohup

By default, when you close a cshw window, any background jobs from that shell get cleaned up too. That's usually what you want — but sometimes you specifically want a job to keep running after you log off.

nohup starts a command in a way that detaches it from your shell:

nohup long_running_server.exe &

The process is started as detached from the console. Closing the shell that started it leaves it running.

A few practical patterns:

nohup backup.cshw &                          # start backup, then close shell
nohup server.exe > server.log 2>&1 &         # explicit output capture
nohup important-job.cshw &                   # leave running overnight

Without explicit redirection, nohup-spawned processes' stdout/stderr goes to nohup.out in the current directory (creating the file if needed). With explicit redirection, you control where the output goes — usually the better choice for anything you want to inspect later.

WARNING

nohup'd processes are detached — they're no longer in your cshw jobs list once your shell exits. To find them again later, use processlist or Task Manager. To terminate them later, use kill PID with the PID Windows assigned. There's no nohup-jobs to bring them back into your shell.


Adjusting Priority: nice

When a background job runs, by default it competes equally with your foreground work for CPU. If the background job is a CPU-heavy compile or a data import, that can make the foreground feel sluggish. nice is the answer — it starts a command at a lower scheduling priority, so it only takes CPU when nothing more important needs it.

nice compress.exe huge_archive       # default lower-priority
nice -n 15 backup.cshw &             # very low priority
nice -n 19 long_job.exe              # lowest priority (idle)

The -n N flag sets how nice the process is — higher numbers mean nicer (more willing to step aside for other work):

Going negative (-n -5, for example) raises priority — useful for a process that needs to be responsive — but typically requires Administrator privileges on Windows.

TECHNICAL STUFF

Windows has fewer priority levels than Unix, so cshw maps the -20..19 nice range onto Windows priority classes (idle, below normal, normal, above normal, high, real-time). nice -n 19 is "idle priority" — your background job runs only when CPU is otherwise free, never stealing time from a foreground process. It's the right choice for "do this, but never let me notice."


Notifications: notify

When a background job finishes, by default you don't hear about it until your next prompt — at which point cshw mentions the completion before showing the next >. If you want to be told immediately, notify enables async notifications:

notify on               # enable async job-completion notifications
notify off              # disable them
notify                  # show current setting

With notify on, a finished background job interrupts whatever you're typing to print its completion line, then puts your cursor back where it was. Useful when you have several background jobs of varying length and want to know the moment each one finishes.


The System View: processlist and ps

Everything we've covered so far is shell-local — jobs are this shell's children, kill 1 means "kill the first job in this shell's list." But sometimes you need the system-wide view: every process running on the machine, started by any user, including processes that aren't connected to any shell.

processlist (alias: ps) lists every process on the system:

processlist

Output:

PID    PPID   Name             Threads  Memory
1234   1      System.exe       12       1.2 MB
2348   1234   svchost.exe      8        12.4 MB
4912   2348   chrome.exe       24       1.8 GB
...

The columns: PID (process ID), PPID (parent process ID — who started this one), name, thread count, memory (working set).

Filtering and sorting

processlist | grep chrome              # only chrome-related processes
processlist /s memory                  # sort by memory usage
processlist /v                         # verbose -- includes full paths

The grep pipeline is the most common idiom — when you want to find one process by name, pipe processlist to grep (or grep -i for case-insensitive). The PID you find can go straight into kill.

processlist | grep notepad
# Found notepad.exe with PID 5678
kill 5678

TIP

processlist | grep -i myapp is the cshw equivalent of "find what's running and tell me the PID." Combined with kill, it's the standard "find and terminate" workflow when your local jobs list doesn't have what you want.

TRY IT

Run processlist | head -n 20 to see the first 20 processes on your system. Look at the PPID column — you should see chains of parent/child relationships (svchost children of services.exe, browser tabs as children of the main browser process, etc.). It's a useful mental model of how processes relate.


A Practical Workflow

Pulling all of this together. Suppose you're working on a project that needs a long build, plus a separate data import, plus you want to keep editing files in the meantime:

# Kick off the build at low priority so it doesn't slow my typing
nice -n 15 build.cshw > build.log 2>&1 &
                                        # [1] 14820

# Start the data import similarly
nice -n 15 import-data.cshw > import.log 2>&1 &
                                        # [2] 14828

# Turn on notifications so I know the moment each finishes
notify on

# Now I work on whatever I want, with the prompt available the whole time.
# After a while...
jobs                                    # check status

# Build's done; let me look at the log
type build.log | tail -n 50

# Import's still going. Bring it forward to watch the last bit
fg 2

# (later, want to stop something)
kill 2

A working example of "many things at once" that's now possible. No new tools beyond what we've covered in this chapter, all composing cleanly.


Honest Limits

A few things worth flagging:


Onward

That's job control. You can now start things in the background, juggle several at once, suspend and resume, prioritize, and terminate cleanly. It's a small but well-loved set of tools that's been around the Unix world for decades — the cshw versions follow the conventions closely.

Chapter 14 picks up where this leaves off and takes it much further. Coroutines are like background jobs, but for procedures rather than external commands — concurrent execution of cshw code, with proper synchronization, result-passing, and a per-thread variable model. If & is "run this external program in parallel," coroutines are "run this procedure in parallel" — and they let you do real multi-threaded work entirely inside the shell, without spawning subprocesses.

After that, Chapter 15 brings the synchronization primitives (mutexes, events, semaphores, channels) you need to make those coroutines play nicely together. By the end of those two chapters you'll be writing shell scripts that genuinely run multiple things at the same time — not just "in the background," but concurrently, with controlled coordination.

That's where cshw stops looking like a shell and starts looking like a real concurrent programming platform. See you in Chapter 14.