How to ensure async subprocess ends with Julia?

Suppose I do something like this

proc = open(`long_running_command`)

How can I ensure that the process exits when Julia does?

If I just open it, the process will outlive Julia.

Is the process something you can communicate with to signal it should shut down itself, or are you looking to just kill it?

Just need to kill it.

The process starts a webserver that I send requests to, but doesn’t have any state that requires it to shut down gracefully.

Something like @at_julia_end kill(proc) would be great if @at_julia_end registers the argument to be run at shutdown

Either of these should work:

help?> atexit
search: atexit CapturedException InvalidStateException

  atexit(f)

  Register a zero-argument function f() to be called at process exit. atexit() hooks are called in last in first out (LIFO) order and run before object finalizers.

help?> finalizer
search: finalizer UndefInitializer finalize

  finalizer(f, x)

  Register a function f(x) to be called when there are no program-accessible references to x, and return x. The type of x must be a mutable struct, otherwise the behavior of this function is unpredictable.

You’d have to register a function that’s manually killing the process you created though.

1 Like

Excellent, thank you!