Search code examples
cprocesslibuv

libuv - What is the difference between `uv_kill` and `uv_process_kill`?


int uv_process_kill(uv_process_t* handle, int signum)

Sends the specified signal to the given process handle. Check the documentation on uv_signal_t — Signal handle for signal support, specially on Windows.

int uv_kill(int pid, int signum)

Sends the specified signal to the given PID. Check the documentation on uv_signal_t — Signal handle for signal support, specially on Windows.

Are these two ways of doing the exact same thing, or is the mechanism inside the library somehow different? I need to handle the error condition where my UV loop may have failed to run (for whatever reason), but I have already called uv_spawn for all the processes I wish to spawn.

My goal is to clean up the resources allocated to the child processes, without needing to know if the uv loop is running, stopped or in an error state.


Solution

  • uv_process_kill and uv_kill perform the same action, but they differ from each other because of their interface. The former accepts an uv_process_t handle while the latter requires a pid explicitly (both have a second argument that is a signal number).
    It's worth noting that the struct uv_process_t (that you can use with uv_process_kill) has a field named pid (that you can use with uv_kill), thus one could argue that the two functions are redundant.
    Anyway, the pid of the process to be killed could come to hand because of an external source (as an example, an user could provide it through the command line - think at how the kill tool works on Linux). Therefore, there is no guarantee that you have an instance of uv_process_t whenever you have a pid and it goes without saying that the two functions serve slightly different purposes.
    Of course, you can still use uv_kill when you have an instance of uv_process_t as:

    uv_kill(proc.pid);
    

    Anyway this is not the way libuv works and you should ever use the functions that accept uv_* data structures when you have them, for they know how to tear down everything correctly.

    To sum up, you can think at uv_process_kill as a more libuv oriented function to be used when you are in charge of the whole lifecycle of the process (you spawn it and you kill it if needed). On the other side, uv_kill is a more general purpose function to be used when you want to deal with processes of which you know the pid but for which you don't have a properly initialized uv_process_t.