lua-users home
lua-l archive

Re: How to detect whether a process is running, on Linux, in the manner of 'pidof'?

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I don't think kill() is going to help you, it requires a PID
as its argument, if you knew the PID, you would be done.
Here are two examples using the information in /proc:
 pidof_cmd() compares the first argument /proc/{PID}/cmdline
 pidof_exe() compares the link referenced by /proc/{PID}/exe
Both return a table of all PIDs matching the search criteria.
Not heavily tested, probably not a one-size-fits-all solution, but maybe
good enough depending on your use case.
#!/usr/bin/env lua
local posix=require 'posix'
local glob = posix.glob
function pidof_cmd(cmd)
 local pids={}
 for _, p in pairs(glob('/proc/[0-9]*/cmdline', 0)) do
 local f=io.open(p)
 if f then
 local s=f:read('*a')
 if s and #s>0 then
 s=s:gsub('0円.*$','')
 if s==cmd then
 table.insert(pids,(p:gsub('^/proc/(%d+)/.*$', '%1')))
 end
 end
 end
 end
 return pids
end
function pidof_exe(exe)
 local pids={}
 for _, p in pairs(glob('/proc/[0-9]*/exe', 0)) do
 local s=posix.readlink(p)
 if s==exe then
 table.insert(pids,(p:gsub('^/proc/(%d+)/.*$', '%1')))
 end
 end
 return pids
end
local cmd=arg[1]
local pidlist=pidof_exe(cmd)
for i,pid in ipairs(pidlist) do
 print(pid)
end
 -- Jeff

AltStyle によって変換されたページ (->オリジナル) /