How to check if a pid is currently running?

I want to confirm that a specific program is running. The other program can write its pid to a file, so I can read that. Is there an existing API (not platform specific) in Julia to confirm that a certain pid (or process by some other query, maybe name or something) is running?

Assuming you are using Linux, you can use kill -0 $PID:

julia> run(`kill -0 43181`)
Process(`kill -0 43181`, ProcessExited(0))

julia> run(`kill -0 43182`)
kill: (43182): No such process
ERROR: failed process: Process(`kill -0 43182`, ProcessExited(1)) [1]

Stacktrace:
 [1] pipeline_error
   @ ./process.jl:531 [inlined]
 [2] run(::Cmd; wait::Bool)
   @ Base ./process.jl:446
 [3] run(::Cmd)
   @ Base ./process.jl:444
 [4] top-level scope
   @ REPL[2]:1

I’m not using Linux. Sorry, I should have specified I was asking if there was an API for it.

You can ccall uv_kill:

ccall(:uv_kill, Cint, (Cint, Cint), getpid(), 0)
2 Likes

I don’t see one on the documentation, but you might try calling uv_kill directly with

julia> @ccall uv_kill(43181::Cint, 0::Cint)::Cint
0

julia> @ccall uv_kill(43182::Cint, 0::Cint)::Cint
-3

Documentation says it might work on Windows, worth a test!

Edit: Oops, sniped!

2 Likes

I think I have a solution, but first a caveat, it doesn’t seem robust what you want to do.

The max PID in at least Linux (where it’s configurable) is 32768 so lets say the process dies, there’s a possibility that some new process will have started with that PID. Might need to have been many, unless something close to the max number of PIDs already in use.

You can change (infor for LInux), to make less likely, see here:

What you can do with Linux/Unix kill (or uv_kill, I see already suggested), you can also do with the underlying kill in C (and thus somehow with ccall from Julia). I do not know the pros and cons vs uv_kill that is just an abstraction.

$ man 2 kill
       #include <sys/types.h>
       #include <signal.h>

       int kill(pid_t pid, int sig);
[..]
       If sig is 0, then no signal is sent, but existence and permission checks are still performed; this can be used to check for the existence of a  process  ID
       or process group ID that the caller is permitted to signal.

I don’t know which signals are portable according to C or POSIX. From way back I recall Windows described as POSIX compatible. From memory that support wasn’t really useful to call Windows sort of Unix compatible, or only just barely. That has since changed with WSL [2], but you want this to work in Windows without using any WSL.

That’s a really good point. I would need to add some other mechanism to ensure it’s the same process. I could have the writing process touch the file occasionally and then the reading process would verify the last modified date of the file is less than the touch period.

I confirmed this works on windows. It returns 0 if found, -4040 if not.