Last active
February 25, 2016 14:01
-
-
Save dpwiz/e6c16dec877368639ee2 to your computer and use it in GitHub Desktop.
Check local registry for a process and spawn one if necessary.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Distributed.Process | |
import Control.Distributed.Process | |
spawnLocalOrHandoff :: String -> Process () -> Process ProcessId | |
spawnLocalOrHandoff regKey proc = do | |
(pidTo, pidFrom) <- newChan | |
pid <- spawnLocal $ registerOrHandoff regKey pidTo proc | |
withMonitor pid $ receiveWait | |
[ matchChan pidFrom $ either die pure | |
, matchIf | |
( \(ProcessMonitorNotification _ mpid r) -> | |
mpid == pid && r /= DiedNormal | |
) | |
$ \_ -> die | |
("Process crashed while attempting registration." :: String) | |
] | |
registerOrHandoff :: String -> SendPort (Either String ProcessId) -> Process () -> Process () | |
registerOrHandoff regKey pidTo proc = do | |
myself <- getSelfPid | |
res <- try $ register regKey myself | |
case res of | |
Right () -> | |
sendChan pidTo (Right myself) >> proc | |
Left (ProcessRegistrationException _ (Just someone)) -> | |
sendChan pidTo (Right someone) | |
Left _ -> | |
sendChan pidTo . Left $ concat | |
[ "Registration for " | |
, regKey | |
, " failed without hand-off pid provided." | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment