add lsof interface

Uses lsof -F0 to get machine-readable output
This commit is contained in:
Joey Hess 2012-06-15 15:13:31 -04:00
parent 4b2b5e820e
commit 85db1720e9

View file

@ -14,17 +14,20 @@ import Common
import System.Cmd.Utils import System.Cmd.Utils
import System.Posix.Types import System.Posix.Types
data OpenMode = ReadWrite | ReadOnly | WriteOnly | Unknown data LsofOpenMode = OpenReadWrite | OpenReadOnly | OpenWriteOnly | OpenUnknown
deriving (Show)
type CmdLine = String type CmdLine = String
data ProcessInfo = ProcessInfo ProcessID CmdLine data ProcessInfo = ProcessInfo ProcessID CmdLine
deriving (Show)
query :: FilePath -> IO [(FilePath, OpenMode, ProcessInfo)] query :: FilePath -> IO [(FilePath, LsofOpenMode, ProcessInfo)]
query p = do query p = do
(h, s) <- pipeFrom "lsof" ["-F0can", "--", p] (pid, s) <- pipeFrom "lsof" ["-F0can", "--", p]
!r <- parse s let !r = parse s
forceSuccess h -- ignore nonzero exit code; lsof returns that when no files are open
void $ getProcessStatus True False $ processID pid
return r return r
{- Parsing null-delimited output like: {- Parsing null-delimited output like:
@ -37,35 +40,42 @@ query p = do
- Where each new process block is started by a pid, and a process can - Where each new process block is started by a pid, and a process can
- have multiple files open. - have multiple files open.
-} -}
parse :: String -> [(FilePath, OpenMode, ProcessInfo)] parse :: String -> [(FilePath, LsofOpenMode, ProcessInfo)]
parse s = go [] $ lines s parse s = bundle $ go [] $ lines s
where where
bundle = concatMap (\(fs, p) -> map (\(f, m) -> (f, m, p)) fs)
go c [] = c go c [] = c
go c (l@(t:r):ls) go c (l@(t:r):ls)
| t == 'p' = parseprocess r | t == 'p' =
let (fs, ls') = parsefiles [] ls
in go ((fs, parseprocess r):c) ls'
| otherwise = parsefail | otherwise = parsefail
go _ _ = parsefail go _ _ = parsefail
parseprocess l = parseprocess l =
case splitnull l of case splitnull l of
[pid, 'c':cmdline] -> [pid, 'c':cmdline, ""] ->
case readish pid of case readish pid of
(Just n) -> ProcessInfo n cmdline (Just n) -> ProcessInfo n cmdline
Nothing -> parsefail Nothing -> parsefail
_ -> parsefail _ -> parsefail
parsefile l = parsefiles c [] = (c, [])
parsefiles c (l:ls) =
case splitnull l of case splitnull l of
['a':mode, 'n':file] -> (file, parsemode mode) ['a':mode, 'n':file, ""] ->
parsefiles ((file, parsemode mode):c) ls
(('p':_):_) -> (c, l:ls)
_ -> parsefail _ -> parsefail
parsemode ('r':_) = ReadOnly parsemode ('r':_) = OpenReadOnly
parsemode ('w':_) = WriteOnly parsemode ('w':_) = OpenWriteOnly
parsemode ('u':_) = ReadWrite parsemode ('u':_) = OpenReadWrite
parsemode _ = Unknown parsemode _ = OpenUnknown
ls = lines s ls = lines s
splitnull = split "\0" splitnull = split "\0"
parsefail = error "failed to parse lsof output: " ++ show s parsefail = error $ "failed to parse lsof output: " ++ show s