How to Make a Batch CLI Safe to Stop Halfway and Rerun
You start a tool on 4,000 files, notice something at file 1,300 and hit Ctrl-C. Is file 1,300 complete? Can you run it again? If the answer is "probably", the tool has a bug that only shows up when you are already having a bad day.
Catching the signal is the easy part. The real goal is that stopping at any instant leaves a state the next run understands, because kill -9, the OOM killer and a flat battery never ask your signal handler for its opinion.
Decide what "done" looks like on disk
Our example compresses a list of files into an output directory. The rule is simple: if the final filename exists, that item is finished. To make that true, a file must never appear under its final name until it is complete.
So each item goes through these steps:
- Write to a temporary file in the output directory.
- Sync it, close it and check both errors.
- Rename it to the final name, which is atomic within one filesystem.
- Sync the directory, so the rename itself survives a power cut.
There is no progress file to drift out of step with reality. The outputs are the checkpoint.
The whole program fits on a page or two
This is Go with only the standard library, written for Linux.
package main
import (
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/signal"
"path/filepath"
"syscall"
)
func main() {
if len(os.Args) < 3 {
fmt.Fprintln(os.Stderr, "usage: batchgz OUTDIR FILE...")
os.Exit(2)
}
ctx, cancel := context.WithCancelCause(context.Background())
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
go func() {
s := <-sigs
signal.Stop(sigs) // a second signal now kills us outright
cancel(signalError{s.(syscall.Signal)})
fmt.Fprintf(os.Stderr, "\n%v: finishing current file (repeat to force quit)\n", s)
}()
err := run(ctx, os.Args[1], os.Args[2:])
if err == nil {
return
}
fmt.Fprintln(os.Stderr, "batchgz:", err)
var se signalError
if errors.As(err, &se) {
os.Exit(128 + int(se.sig))
}
os.Exit(1)
}
type signalError struct{ sig syscall.Signal }
func (e signalError) Error() string { return "stopped by " + e.sig.String() }
func run(ctx context.Context, outDir string, inputs []string) error {
// Two inputs with one base name would look "already done": refuse early.
seen := make(map[string]bool)
for _, in := range inputs {
name := filepath.Base(in)
if seen[name] {
return fmt.Errorf("duplicate file name %q", name)
}
seen[name] = true
}
for i, in := range inputs {
if ctx.Err() != nil {
return fmt.Errorf("%d of %d done, rerun to resume: %w",
i, len(inputs), context.Cause(ctx))
}
out := filepath.Join(outDir, filepath.Base(in)+".gz")
_, err := os.Stat(out)
if err == nil {
continue // finished on an earlier run
}
if !errors.Is(err, fs.ErrNotExist) {
return err
}
if err := compress(in, out); err != nil {
return fmt.Errorf("%s: %w", in, err)
}
}
return nil
}
func compress(in, out string) (err error) {
src, err := os.Open(in)
if err != nil {
return err
}
defer src.Close()
// Same directory as the target, so the rename stays on one filesystem.
tmp, err := os.CreateTemp(filepath.Dir(out), ".tmp-*")
if err != nil {
return err
}
defer func() {
if err != nil {
tmp.Close()
os.Remove(tmp.Name())
}
}()
zw := gzip.NewWriter(tmp)
if _, err = io.Copy(zw, src); err != nil {
return err
}
if err = zw.Close(); err != nil {
return err
}
if err = tmp.Sync(); err != nil {
return err
}
if err = tmp.Close(); err != nil {
return err
}
if err = os.Rename(tmp.Name(), out); err != nil {
return err
}
return syncDir(filepath.Dir(out))
}
func syncDir(path string) error {
d, err := os.Open(path)
if err != nil {
return err
}
defer d.Close()
return d.Sync()
}
The first Ctrl-C asks, the second one insists
The first signal cancels a context, which the loop checks between items. The current file finishes, the tool says how far it got, and nothing new starts. If the signal arrives during the last file, the job simply completes and exits 0.
Always leave the user a way to force the issue. signal.Stop stops delivery to our channel, so with no other subscribers a second Ctrl-C gets the default behaviour and kills the process. That matters when "finish the current item" turns out to mean twenty minutes.
The popular signal.NotifyContext is shorter, but you must call its stop function after cancellation to get that second-press behaviour. If you defer it to the end of main, repeat presses are swallowed while you are still working.
If one item can take ages, pass the context into the work and abandon the temporary file. For short items, finishing is simpler and wastes less.
Exit like something that was interrupted
A stopped job must not exit 0, or batchgz out *.log && rm *.log becomes an exciting command. The program uses 128 plus the signal number: 130 for SIGINT and 143 for SIGTERM.
Quick detour, because this is odd: exiting with 130 differs from being killed by SIGINT, although $? shows 130 for both. A parent can tell them apart. Bash uses this to decide whether Ctrl-C should abort a whole script, so a loop around your tool may carry on to the next iteration after a polite exit.
If that matters, reset the handler after cleaning up and send yourself the same signal. For a tool mostly run by hand or by a service manager, the plain exit code is often enough.
Child processes hear Ctrl-C too
Ctrl-C in a terminal signals the whole foreground process group, including your program's children. If your batch tool runs ffmpeg or pg_dump for each item, the child receives SIGINT while you are politely waiting for it to finish.
Your options are:
- Let the child stop, treat its failure as an unfinished item and discard the partial output.
- Start it in its own process group with
SysProcAttr{Setpgid: true}, then take responsibility for killing it, including on a forced quit.
I would take the first. Never rename output into place unless the child exited successfully. Also note that exec.CommandContext kills the child on cancellation by default, which is not "finish the current item".
Test it by being rude to it
Give it enough large files to keep it busy for a second or so, then interrupt it part-way. Adjust the delay to suit your machine.
mkdir -p out
timeout --foreground --preserve-status -s INT 0.5 ./batchgz out in/*
echo $? # 130 if it was still working
ls -A out
./batchgz out in/*
for f in in/*; do gzip -dc "out/${f#in/}.gz" | cmp - "$f"; done
The --foreground flag makes timeout signal only the command, which avoids an accidental double press. The final loop should print nothing.
Now repeat with -s KILL. You should see only complete .gz files, perhaps alongside a .tmp- file. The rerun fills in the gaps. A forced second Ctrl-C leaves the same sort of debris.
Where "the file exists" stops being enough
This design only knows that an output was completed; it cannot tell whether the output is still correct. Check these before borrowing it:
- If an input changes, the old output is still skipped. Record a content hash, or use a fresh output directory.
- If you change the processing logic, old results remain. Put a version in the output path.
- Leftover temporary files are harmless but take space. Only delete them automatically if a lock guarantees no other copy is running.
os.CreateTempcreates files with mode 0600 (before the umask), and rename keeps it. Change the mode first if others need to read the output.
Jobs that send email, charge cards or call an API are harder, since there is no file to rename. Durably record "about to do item 42" before the call and "did item 42" afterwards.
A crash between those two leaves the result unknown. Retrying is safe only if the other end accepts an idempotency key or lets you ask what happened. No amount of signal handling closes that gap, so have the tool report those items instead of guessing.