How to get the process id of the created process in Haskell?

Maybe I just missed something obvious in the System.Process API ( http://hackage.haskell.org/package/process ), but it doesn't seem to support getting the original PID of the created process. The API usually returns a ProcessHandle, which can be used quite easily, but this does not seem to match the deployment needs that I have.

I have a case where I want to start a long process, register the PID that it uses, and be able to automatically return at a later time (days, weeks, months) and kill the old process, start with a new process. I'm sure there are several ways to do this automatically deploy and restart, but the PIDs looked like the easiest way to do this without too much platform-specific code.

I am open to other suggestions on my main problem, but it seems strange to me that I cannot find direct PID links (or a way to convert them) into the process API. This is similar to API control.

+6
source share
3 answers

Here is a sample code:

import System.Process import System.Process.Internals -- | returns Just pid or Nothing if process has already exited getPid ph = withProcessHandle ph go where go ph_ = case ph_ of OpenHandle x -> return $ Just x ClosedHandle _ -> return Nothing main = do (_,_,_,ph) <- createProcess $ shell "echo $$" getPid ph >>= print 

Note. I have not tested this under Windows, but it works on OSX and, presumably, on Linux.

For Windows, the Win32 package has the getProcessId function in the System.Win32.Process module, and according to the code I read, this should work:

 import System.Win32.Process (getProcessId) main = do (_,_,_,ph) <- createProcess $ shell "echo $$" pid <- withProcessHandle ph go print pid where go (OpenHandle x) = fmap Just $ getProcessId x go (ClosedHandle _) = return Nothing 

The code I'm building on this is the code for interruptProcessGroupOf (link)

+4
source

It looks like the interruptProcessGroupOf in System.Process calls either System.Posix.Process.getProcessGroupIDOf (POSIX / not Windows) or System.Win32.Process.getProcessId (Windows) to get pid: http://git.haskell.org/packages /process.git/blob/HEAD:/System/Process.hs

+3
source

If all else fails,

 import System.Process.Internals 

and then ProcessHandle abstraction. You probably want to extract PHANDLE from MVar .

Please note that this violates the level of abstraction, which is designed to transfer code through the OS. Use it with extreme caution and be prepared to break it in new versions of the library.

0
source

Source: https://habr.com/ru/post/979360/


All Articles