a8e627ad6d2fb820342ff92b943758debd8cb39d
[packages/process.git] / System / Process.hs
1 {-# LANGUAGE CPP, ForeignFunctionInterface #-}
2 #if __GLASGOW_HASKELL__ >= 709
3 {-# LANGUAGE Safe #-}
4 #else
5 {-# LANGUAGE Trustworthy #-}
6 #endif
7 {-# LANGUAGE InterruptibleFFI #-}
8
9 -----------------------------------------------------------------------------
10 -- |
11 -- Module : System.Process
12 -- Copyright : (c) The University of Glasgow 2004-2008
13 -- License : BSD-style (see the file libraries/base/LICENSE)
14 --
15 -- Maintainer : libraries@haskell.org
16 -- Stability : experimental
17 -- Portability : non-portable (requires concurrency)
18 --
19 -- Operations for creating and interacting with sub-processes.
20 --
21 -----------------------------------------------------------------------------
22
23 -- ToDo:
24 -- * Flag to control whether exiting the parent also kills the child.
25
26 module System.Process (
27 -- * Running sub-processes
28 createProcess,
29 createProcess_,
30 shell, proc,
31 CreateProcess(..),
32 CmdSpec(..),
33 StdStream(..),
34 ProcessHandle,
35
36 -- ** Simpler functions for common tasks
37 callProcess,
38 callCommand,
39 spawnProcess,
40 spawnCommand,
41 readCreateProcess,
42 readProcess,
43 readCreateProcessWithExitCode,
44 readProcessWithExitCode,
45 withCreateProcess,
46
47 -- ** Related utilities
48 showCommandForUser,
49
50 -- ** Control-C handling on Unix
51 -- $ctlc-handling
52
53 -- * Process completion
54 waitForProcess,
55 getProcessExitCode,
56 terminateProcess,
57 interruptProcessGroupOf,
58
59 -- Interprocess communication
60 createPipe,
61 createPipeFd,
62
63 -- * Old deprecated functions
64 -- | These functions pre-date 'createProcess' which is much more
65 -- flexible.
66 runProcess,
67 runCommand,
68 runInteractiveProcess,
69 runInteractiveCommand,
70 system,
71 rawSystem,
72 ) where
73
74 import Prelude hiding (mapM)
75
76 import System.Process.Internals
77
78 import Control.Concurrent
79 import Control.DeepSeq (rnf)
80 import Control.Exception (SomeException, mask, allowInterrupt, bracket, try, throwIO)
81 import qualified Control.Exception as C
82 import Control.Monad
83 import Data.Maybe
84 import Foreign
85 import Foreign.C
86 import System.Exit ( ExitCode(..) )
87 import System.IO
88 import System.IO.Error (mkIOError, ioeSetErrorString)
89
90 -- Provide the data constructors for CPid on GHC 7.4 and later
91 #if !defined(WINDOWS) && MIN_VERSION_base(4,5,0)
92 import System.Posix.Types (CPid (..))
93 #endif
94
95 import GHC.IO.Exception ( ioException, IOErrorType(..), IOException(..) )
96
97 -- ----------------------------------------------------------------------------
98 -- createProcess
99
100 -- | Construct a 'CreateProcess' record for passing to 'createProcess',
101 -- representing a raw command with arguments.
102 --
103 -- See 'RawCommand' for precise semantics of the specified @FilePath@.
104 proc :: FilePath -> [String] -> CreateProcess
105 proc cmd args = CreateProcess { cmdspec = RawCommand cmd args,
106 cwd = Nothing,
107 env = Nothing,
108 std_in = Inherit,
109 std_out = Inherit,
110 std_err = Inherit,
111 close_fds = False,
112 create_group = False,
113 delegate_ctlc = False,
114 detach_console = False,
115 create_new_console = False,
116 new_session = False,
117 child_group = Nothing,
118 child_user = Nothing,
119 use_process_jobs = False }
120
121 -- | Construct a 'CreateProcess' record for passing to 'createProcess',
122 -- representing a command to be passed to the shell.
123 shell :: String -> CreateProcess
124 shell str = CreateProcess { cmdspec = ShellCommand str,
125 cwd = Nothing,
126 env = Nothing,
127 std_in = Inherit,
128 std_out = Inherit,
129 std_err = Inherit,
130 close_fds = False,
131 create_group = False,
132 delegate_ctlc = False,
133 detach_console = False,
134 create_new_console = False,
135 new_session = False,
136 child_group = Nothing,
137 child_user = Nothing,
138 use_process_jobs = False }
139
140 {- |
141 This is the most general way to spawn an external process. The
142 process can be a command line to be executed by a shell or a raw command
143 with a list of arguments. The stdin, stdout, and stderr streams of
144 the new process may individually be attached to new pipes, to existing
145 'Handle's, or just inherited from the parent (the default.)
146
147 The details of how to create the process are passed in the
148 'CreateProcess' record. To make it easier to construct a
149 'CreateProcess', the functions 'proc' and 'shell' are supplied that
150 fill in the fields with default values which can be overriden as
151 needed.
152
153 'createProcess' returns @(/mb_stdin_hdl/, /mb_stdout_hdl/, /mb_stderr_hdl/, /ph/)@,
154 where
155
156 * if @'std_in' == 'CreatePipe'@, then @/mb_stdin_hdl/@ will be @Just /h/@,
157 where @/h/@ is the write end of the pipe connected to the child
158 process's @stdin@.
159
160 * otherwise, @/mb_stdin_hdl/ == Nothing@
161
162 Similarly for @/mb_stdout_hdl/@ and @/mb_stderr_hdl/@.
163
164 For example, to execute a simple @ls@ command:
165
166 > r <- createProcess (proc "ls" [])
167
168 To create a pipe from which to read the output of @ls@:
169
170 > (_, Just hout, _, _) <-
171 > createProcess (proc "ls" []){ std_out = CreatePipe }
172
173 To also set the directory in which to run @ls@:
174
175 > (_, Just hout, _, _) <-
176 > createProcess (proc "ls" []){ cwd = Just "\home\bob",
177 > std_out = CreatePipe }
178
179 Note that @Handle@s provided for @std_in@, @std_out@, or @std_err@ via the
180 @UseHandle@ constructor will be closed by calling this function. This is not
181 always the desired behavior. In cases where you would like to leave the
182 @Handle@ open after spawning the child process, please use 'createProcess_'
183 instead. All created @Handle@s are initially in text mode; if you need them
184 to be in binary mode then use 'hSetBinaryMode'.
185
186 -}
187 createProcess
188 :: CreateProcess
189 -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
190 createProcess cp = do
191 r <- createProcess_ "createProcess" cp
192 maybeCloseStd (std_in cp)
193 maybeCloseStd (std_out cp)
194 maybeCloseStd (std_err cp)
195 return r
196 where
197 maybeCloseStd :: StdStream -> IO ()
198 maybeCloseStd (UseHandle hdl)
199 | hdl /= stdin && hdl /= stdout && hdl /= stderr = hClose hdl
200 maybeCloseStd _ = return ()
201
202 -- | A 'C.bracket'-style resource handler for 'createProcess'.
203 --
204 -- Does automatic cleanup when the action finishes. If there is an exception
205 -- in the body then it ensures that the process gets terminated and any
206 -- 'CreatePipe' 'Handle's are closed. In particular this means that if the
207 -- Haskell thread is killed (e.g. 'killThread'), that the external process is
208 -- also terminated.
209 --
210 -- e.g.
211 --
212 -- > withCreateProcess (proc cmd args) { ... } $ \stdin stdout stderr ph -> do
213 -- > ...
214 --
215 -- @since 1.4.3.0
216 withCreateProcess
217 :: CreateProcess
218 -> (Maybe Handle -> Maybe Handle -> Maybe Handle -> ProcessHandle -> IO a)
219 -> IO a
220 withCreateProcess c action =
221 C.bracket (createProcess c) cleanupProcess
222 (\(m_in, m_out, m_err, ph) -> action m_in m_out m_err ph)
223
224 -- wrapper so we can get exceptions with the appropriate function name.
225 withCreateProcess_
226 :: String
227 -> CreateProcess
228 -> (Maybe Handle -> Maybe Handle -> Maybe Handle -> ProcessHandle -> IO a)
229 -> IO a
230 withCreateProcess_ fun c action =
231 C.bracketOnError (createProcess_ fun c) cleanupProcess
232 (\(m_in, m_out, m_err, ph) -> action m_in m_out m_err ph)
233
234
235 cleanupProcess :: (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
236 -> IO ()
237 cleanupProcess (mb_stdin, mb_stdout, mb_stderr,
238 ph@(ProcessHandle _ delegating_ctlc _)) = do
239 terminateProcess ph
240 -- Note, it's important that other threads that might be reading/writing
241 -- these handles also get killed off, since otherwise they might be holding
242 -- the handle lock and prevent us from closing, leading to deadlock.
243 maybe (return ()) (ignoreSigPipe . hClose) mb_stdin
244 maybe (return ()) hClose mb_stdout
245 maybe (return ()) hClose mb_stderr
246 -- terminateProcess does not guarantee that it terminates the process.
247 -- Indeed on Unix it's SIGTERM, which asks nicely but does not guarantee
248 -- that it stops. If it doesn't stop, we don't want to hang, so we wait
249 -- asynchronously using forkIO.
250
251 -- However we want to end the Ctl-C handling synchronously, so we'll do
252 -- that synchronously, and set delegating_ctlc as False for the
253 -- waitForProcess (which would otherwise end the Ctl-C delegation itself).
254 when delegating_ctlc
255 stopDelegateControlC
256 _ <- forkIO (waitForProcess (resetCtlcDelegation ph) >> return ())
257 return ()
258 where
259 resetCtlcDelegation (ProcessHandle m _ l) = ProcessHandle m False l
260
261 -- ----------------------------------------------------------------------------
262 -- spawnProcess/spawnCommand
263
264 -- | Creates a new process to run the specified raw command with the given
265 -- arguments. It does not wait for the program to finish, but returns the
266 -- 'ProcessHandle'.
267 --
268 -- @since 1.2.0.0
269 spawnProcess :: FilePath -> [String] -> IO ProcessHandle
270 spawnProcess cmd args = do
271 (_,_,_,p) <- createProcess_ "spawnProcess" (proc cmd args)
272 return p
273
274 -- | Creates a new process to run the specified shell command.
275 -- It does not wait for the program to finish, but returns the 'ProcessHandle'.
276 --
277 -- @since 1.2.0.0
278 spawnCommand :: String -> IO ProcessHandle
279 spawnCommand cmd = do
280 (_,_,_,p) <- createProcess_ "spawnCommand" (shell cmd)
281 return p
282
283
284 -- ----------------------------------------------------------------------------
285 -- callProcess/callCommand
286
287 -- | Creates a new process to run the specified command with the given
288 -- arguments, and wait for it to finish. If the command returns a non-zero
289 -- exit code, an exception is raised.
290 --
291 -- If an asynchronous exception is thrown to the thread executing
292 -- @callProcess@, the forked process will be terminated and
293 -- @callProcess@ will wait (block) until the process has been
294 -- terminated.
295 --
296 -- @since 1.2.0.0
297 callProcess :: FilePath -> [String] -> IO ()
298 callProcess cmd args = do
299 exit_code <- withCreateProcess_ "callProcess"
300 (proc cmd args) { delegate_ctlc = True } $ \_ _ _ p ->
301 waitForProcess p
302 case exit_code of
303 ExitSuccess -> return ()
304 ExitFailure r -> processFailedException "callProcess" cmd args r
305
306 -- | Creates a new process to run the specified shell command. If the
307 -- command returns a non-zero exit code, an exception is raised.
308 --
309 -- If an asynchronous exception is thrown to the thread executing
310 -- @callCommand@, the forked process will be terminated and
311 -- @callCommand@ will wait (block) until the process has been
312 -- terminated.
313 --
314 -- @since 1.2.0.0
315 callCommand :: String -> IO ()
316 callCommand cmd = do
317 exit_code <- withCreateProcess_ "callCommand"
318 (shell cmd) { delegate_ctlc = True } $ \_ _ _ p ->
319 waitForProcess p
320 case exit_code of
321 ExitSuccess -> return ()
322 ExitFailure r -> processFailedException "callCommand" cmd [] r
323
324 processFailedException :: String -> String -> [String] -> Int -> IO a
325 processFailedException fun cmd args exit_code =
326 ioError (mkIOError OtherError (fun ++ ": " ++ cmd ++
327 concatMap ((' ':) . show) args ++
328 " (exit " ++ show exit_code ++ ")")
329 Nothing Nothing)
330
331
332 -- ----------------------------------------------------------------------------
333 -- Control-C handling on Unix
334
335 -- $ctlc-handling
336 --
337 -- When running an interactive console process (such as a shell, console-based
338 -- text editor or ghci), we typically want that process to be allowed to handle
339 -- Ctl-C keyboard interrupts how it sees fit. For example, while most programs
340 -- simply quit on a Ctl-C, some handle it specially. To allow this to happen,
341 -- use the @'delegate_ctlc' = True@ option in the 'CreateProcess' options.
342 --
343 -- The gory details:
344 --
345 -- By default Ctl-C will generate a @SIGINT@ signal, causing a 'UserInterrupt'
346 -- exception to be sent to the main Haskell thread of your program, which if
347 -- not specially handled will terminate the program. Normally, this is exactly
348 -- what is wanted: an orderly shutdown of the program in response to Ctl-C.
349 --
350 -- Of course when running another interactive program in the console then we
351 -- want to let that program handle Ctl-C. Under Unix however, Ctl-C sends
352 -- @SIGINT@ to every process using the console. The standard solution is that
353 -- while running an interactive program, ignore @SIGINT@ in the parent, and let
354 -- it be handled in the child process. If that process then terminates due to
355 -- the @SIGINT@ signal, then at that point treat it as if we had recieved the
356 -- @SIGINT@ ourselves and begin an orderly shutdown.
357 --
358 -- This behaviour is implemented by 'createProcess' (and
359 -- 'waitForProcess' \/ 'getProcessExitCode') when the @'delegate_ctlc' = True@
360 -- option is set. In particular, the @SIGINT@ signal will be ignored until
361 -- 'waitForProcess' returns (or 'getProcessExitCode' returns a non-Nothing
362 -- result), so it becomes especially important to use 'waitForProcess' for every
363 -- processes created.
364 --
365 -- In addition, in 'delegate_ctlc' mode, 'waitForProcess' and
366 -- 'getProcessExitCode' will throw a 'UserInterrupt' exception if the process
367 -- terminated with @'ExitFailure' (-SIGINT)@. Typically you will not want to
368 -- catch this exception, but let it propagate, giving a normal orderly shutdown.
369 -- One detail to be aware of is that the 'UserInterrupt' exception is thrown
370 -- /synchronously/ in the thread that calls 'waitForProcess', whereas normally
371 -- @SIGINT@ causes the exception to be thrown /asynchronously/ to the main
372 -- thread.
373 --
374 -- For even more detail on this topic, see
375 -- <http://www.cons.org/cracauer/sigint.html "Proper handling of SIGINT/SIGQUIT">.
376
377 -- -----------------------------------------------------------------------------
378
379 -- | @readProcess@ forks an external process, reads its standard output
380 -- strictly, blocking until the process terminates, and returns the output
381 -- string. The external process inherits the standard error.
382 --
383 -- If an asynchronous exception is thrown to the thread executing
384 -- @readProcess@, the forked process will be terminated and @readProcess@ will
385 -- wait (block) until the process has been terminated.
386 --
387 -- Output is returned strictly, so this is not suitable for
388 -- interactive applications.
389 --
390 -- This function throws an 'IOError' if the process 'ExitCode' is
391 -- anything other than 'ExitSuccess'. If instead you want to get the
392 -- 'ExitCode' then use 'readProcessWithExitCode'.
393 --
394 -- Users of this function should compile with @-threaded@ if they
395 -- want other Haskell threads to keep running while waiting on
396 -- the result of readProcess.
397 --
398 -- > > readProcess "date" [] []
399 -- > "Thu Feb 7 10:03:39 PST 2008\n"
400 --
401 -- The arguments are:
402 --
403 -- * The command to run, which must be in the $PATH, or an absolute or relative path
404 --
405 -- * A list of separate command line arguments to the program
406 --
407 -- * A string to pass on standard input to the forked process.
408 --
409 readProcess
410 :: FilePath -- ^ Filename of the executable (see 'RawCommand' for details)
411 -> [String] -- ^ any arguments
412 -> String -- ^ standard input
413 -> IO String -- ^ stdout
414 readProcess cmd args = readCreateProcess $ proc cmd args
415
416 -- | @readCreateProcess@ works exactly like 'readProcess' except that it
417 -- lets you pass 'CreateProcess' giving better flexibility.
418 --
419 -- > > readCreateProcess (shell "pwd" { cwd = "/etc/" }) ""
420 -- > "/etc\n"
421 --
422 -- Note that @Handle@s provided for @std_in@ or @std_out@ via the CreateProcess
423 -- record will be ignored.
424 --
425 -- @since 1.2.3.0
426
427 readCreateProcess
428 :: CreateProcess
429 -> String -- ^ standard input
430 -> IO String -- ^ stdout
431 readCreateProcess cp input = do
432 let cp_opts = cp {
433 std_in = CreatePipe,
434 std_out = CreatePipe
435 }
436 (ex, output) <- withCreateProcess_ "readCreateProcess" cp_opts $
437 \(Just inh) (Just outh) _ ph -> do
438
439 -- fork off a thread to start consuming the output
440 output <- hGetContents outh
441 withForkWait (C.evaluate $ rnf output) $ \waitOut -> do
442
443 -- now write any input
444 unless (null input) $
445 ignoreSigPipe $ hPutStr inh input
446 -- hClose performs implicit hFlush, and thus may trigger a SIGPIPE
447 ignoreSigPipe $ hClose inh
448
449 -- wait on the output
450 waitOut
451 hClose outh
452
453 -- wait on the process
454 ex <- waitForProcess ph
455 return (ex, output)
456
457 case ex of
458 ExitSuccess -> return output
459 ExitFailure r -> processFailedException "readCreateProcess" cmd args r
460 where
461 cmd = case cp of
462 CreateProcess { cmdspec = ShellCommand sc } -> sc
463 CreateProcess { cmdspec = RawCommand fp _ } -> fp
464 args = case cp of
465 CreateProcess { cmdspec = ShellCommand _ } -> []
466 CreateProcess { cmdspec = RawCommand _ args' } -> args'
467
468
469 -- | @readProcessWithExitCode@ is like @readProcess@ but with two differences:
470 --
471 -- * it returns the 'ExitCode' of the process, and does not throw any
472 -- exception if the code is not 'ExitSuccess'.
473 --
474 -- * it reads and returns the output from process' standard error handle,
475 -- rather than the process inheriting the standard error handle.
476 --
477 -- On Unix systems, see 'waitForProcess' for the meaning of exit codes
478 -- when the process died as the result of a signal.
479 --
480 readProcessWithExitCode
481 :: FilePath -- ^ Filename of the executable (see 'RawCommand' for details)
482 -> [String] -- ^ any arguments
483 -> String -- ^ standard input
484 -> IO (ExitCode,String,String) -- ^ exitcode, stdout, stderr
485 readProcessWithExitCode cmd args =
486 readCreateProcessWithExitCode $ proc cmd args
487
488 -- | @readCreateProcessWithExitCode@ works exactly like 'readProcessWithExitCode' except that it
489 -- lets you pass 'CreateProcess' giving better flexibility.
490 --
491 -- Note that @Handle@s provided for @std_in@, @std_out@, or @std_err@ via the CreateProcess
492 -- record will be ignored.
493 --
494 -- @since 1.2.3.0
495 readCreateProcessWithExitCode
496 :: CreateProcess
497 -> String -- ^ standard input
498 -> IO (ExitCode,String,String) -- ^ exitcode, stdout, stderr
499 readCreateProcessWithExitCode cp input = do
500 let cp_opts = cp {
501 std_in = CreatePipe,
502 std_out = CreatePipe,
503 std_err = CreatePipe
504 }
505 withCreateProcess_ "readCreateProcessWithExitCode" cp_opts $
506 \(Just inh) (Just outh) (Just errh) ph -> do
507
508 out <- hGetContents outh
509 err <- hGetContents errh
510
511 -- fork off threads to start consuming stdout & stderr
512 withForkWait (C.evaluate $ rnf out) $ \waitOut ->
513 withForkWait (C.evaluate $ rnf err) $ \waitErr -> do
514
515 -- now write any input
516 unless (null input) $
517 ignoreSigPipe $ hPutStr inh input
518 -- hClose performs implicit hFlush, and thus may trigger a SIGPIPE
519 ignoreSigPipe $ hClose inh
520
521 -- wait on the output
522 waitOut
523 waitErr
524
525 hClose outh
526 hClose errh
527
528 -- wait on the process
529 ex <- waitForProcess ph
530
531 return (ex, out, err)
532
533 -- | Fork a thread while doing something else, but kill it if there's an
534 -- exception.
535 --
536 -- This is important in the cases above because we want to kill the thread
537 -- that is holding the Handle lock, because when we clean up the process we
538 -- try to close that handle, which could otherwise deadlock.
539 --
540 withForkWait :: IO () -> (IO () -> IO a) -> IO a
541 withForkWait async body = do
542 waitVar <- newEmptyMVar :: IO (MVar (Either SomeException ()))
543 mask $ \restore -> do
544 tid <- forkIO $ try (restore async) >>= putMVar waitVar
545 let wait = takeMVar waitVar >>= either throwIO return
546 restore (body wait) `C.onException` killThread tid
547
548 ignoreSigPipe :: IO () -> IO ()
549 ignoreSigPipe = C.handle $ \e -> case e of
550 IOError { ioe_type = ResourceVanished
551 , ioe_errno = Just ioe }
552 | Errno ioe == ePIPE -> return ()
553 _ -> throwIO e
554
555 -- ----------------------------------------------------------------------------
556 -- showCommandForUser
557
558 -- | Given a program @/p/@ and arguments @/args/@,
559 -- @showCommandForUser /p/ /args/@ returns a string suitable for pasting
560 -- into @\/bin\/sh@ (on Unix systems) or @CMD.EXE@ (on Windows).
561 showCommandForUser :: FilePath -> [String] -> String
562 showCommandForUser cmd args = unwords (map translate (cmd : args))
563
564
565 -- ----------------------------------------------------------------------------
566 -- waitForProcess
567
568 {- | Waits for the specified process to terminate, and returns its exit code.
569
570 GHC Note: in order to call @waitForProcess@ without blocking all the
571 other threads in the system, you must compile the program with
572 @-threaded@.
573
574 (/Since: 1.2.0.0/) On Unix systems, a negative value @'ExitFailure' -/signum/@
575 indicates that the child was terminated by signal @/signum/@.
576 The signal numbers are platform-specific, so to test for a specific signal use
577 the constants provided by "System.Posix.Signals" in the @unix@ package.
578 Note: core dumps are not reported, use "System.Posix.Process" if you need this
579 detail.
580
581 -}
582 waitForProcess
583 :: ProcessHandle
584 -> IO ExitCode
585 waitForProcess ph@(ProcessHandle _ delegating_ctlc _) = lockWaitpid $ do
586 p_ <- modifyProcessHandle ph $ \p_ -> return (p_,p_)
587 case p_ of
588 ClosedHandle e -> return e
589 OpenHandle h -> do
590 e <- alloca $ \pret -> do
591 -- don't hold the MVar while we call c_waitForProcess...
592 throwErrnoIfMinus1Retry_ "waitForProcess" (allowInterrupt >> c_waitForProcess h pret)
593 modifyProcessHandle ph $ \p_' ->
594 case p_' of
595 ClosedHandle e -> return (p_', e)
596 OpenExtHandle{} -> return (p_', ExitFailure (-1))
597 OpenHandle ph' -> do
598 closePHANDLE ph'
599 code <- peek pret
600 let e = if (code == 0)
601 then ExitSuccess
602 else (ExitFailure (fromIntegral code))
603 return (ClosedHandle e, e)
604 when delegating_ctlc $
605 endDelegateControlC e
606 return e
607 #if defined(WINDOWS)
608 OpenExtHandle _ job iocp ->
609 maybe (ExitFailure (-1)) mkExitCode `fmap` waitForJobCompletion job iocp timeout_Infinite
610 where mkExitCode code | code == 0 = ExitSuccess
611 | otherwise = ExitFailure $ fromIntegral code
612 #else
613 OpenExtHandle _ _job _iocp ->
614 return $ ExitFailure (-1)
615 #endif
616 where
617 -- If more than one thread calls `waitpid` at a time, `waitpid` will
618 -- return the exit code to one of them and (-1) to the rest of them,
619 -- causing an exception to be thrown.
620 -- Cf. https://github.com/haskell/process/issues/46, and
621 -- https://github.com/haskell/process/pull/58 for further discussion
622 lockWaitpid m = withMVar (waitpidLock ph) $ \() -> m
623
624 -- ----------------------------------------------------------------------------
625 -- getProcessExitCode
626
627 {- |
628 This is a non-blocking version of 'waitForProcess'. If the process is
629 still running, 'Nothing' is returned. If the process has exited, then
630 @'Just' e@ is returned where @e@ is the exit code of the process.
631
632 On Unix systems, see 'waitForProcess' for the meaning of exit codes
633 when the process died as the result of a signal.
634 -}
635
636 getProcessExitCode :: ProcessHandle -> IO (Maybe ExitCode)
637 getProcessExitCode ph@(ProcessHandle _ delegating_ctlc _) = tryLockWaitpid $ do
638 (m_e, was_open) <- modifyProcessHandle ph $ \p_ ->
639 case p_ of
640 ClosedHandle e -> return (p_, (Just e, False))
641 open -> do
642 alloca $ \pExitCode -> do
643 case getHandle open of
644 Nothing -> return (p_, (Nothing, False))
645 Just h -> do
646 res <- throwErrnoIfMinus1Retry "getProcessExitCode" $
647 c_getProcessExitCode h pExitCode
648 code <- peek pExitCode
649 if res == 0
650 then return (p_, (Nothing, False))
651 else do
652 closePHANDLE h
653 let e | code == 0 = ExitSuccess
654 | otherwise = ExitFailure (fromIntegral code)
655 return (ClosedHandle e, (Just e, True))
656 case m_e of
657 Just e | was_open && delegating_ctlc -> endDelegateControlC e
658 _ -> return ()
659 return m_e
660 where getHandle :: ProcessHandle__ -> Maybe PHANDLE
661 getHandle (OpenHandle h) = Just h
662 getHandle (ClosedHandle _) = Nothing
663 getHandle (OpenExtHandle h _ _) = Just h
664
665 -- If somebody is currently holding the waitpid lock, we don't want to
666 -- accidentally remove the pid from the process table.
667 -- Try acquiring the waitpid lock. If it is held, we are done
668 -- since that means the process is still running and we can return
669 -- `Nothing`. If it is not held, acquire it so we can run the
670 -- (non-blocking) call to `waitpid` without worrying about any
671 -- other threads calling it at the same time.
672 tryLockWaitpid :: IO (Maybe ExitCode) -> IO (Maybe ExitCode)
673 tryLockWaitpid action = bracket acquire release between
674 where
675 acquire = tryTakeMVar (waitpidLock ph)
676 release m = case m of
677 Nothing -> return ()
678 Just () -> putMVar (waitpidLock ph) ()
679 between m = case m of
680 Nothing -> return Nothing
681 Just () -> action
682
683 -- ----------------------------------------------------------------------------
684 -- terminateProcess
685
686 -- | Attempts to terminate the specified process. This function should
687 -- not be used under normal circumstances - no guarantees are given regarding
688 -- how cleanly the process is terminated. To check whether the process
689 -- has indeed terminated, use 'getProcessExitCode'.
690 --
691 -- On Unix systems, 'terminateProcess' sends the process the SIGTERM signal.
692 -- On Windows systems, the Win32 @TerminateProcess@ function is called, passing
693 -- an exit code of 1.
694 --
695 -- Note: on Windows, if the process was a shell command created by
696 -- 'createProcess' with 'shell', or created by 'runCommand' or
697 -- 'runInteractiveCommand', then 'terminateProcess' will only
698 -- terminate the shell, not the command itself. On Unix systems, both
699 -- processes are in a process group and will be terminated together.
700
701 terminateProcess :: ProcessHandle -> IO ()
702 terminateProcess ph = do
703 withProcessHandle ph $ \p_ ->
704 case p_ of
705 ClosedHandle _ -> return ()
706 #if defined(WINDOWS)
707 OpenExtHandle{} -> terminateJob ph 1 >> return ()
708 #else
709 OpenExtHandle{} -> error "terminateProcess with OpenExtHandle should not happen on POSIX."
710 #endif
711 OpenHandle h -> do
712 throwErrnoIfMinus1Retry_ "terminateProcess" $ c_terminateProcess h
713 return ()
714 -- does not close the handle, we might want to try terminating it
715 -- again, or get its exit code.
716
717
718 -- ----------------------------------------------------------------------------
719 -- Interface to C bits
720
721 foreign import ccall unsafe "terminateProcess"
722 c_terminateProcess
723 :: PHANDLE
724 -> IO CInt
725
726 foreign import ccall unsafe "getProcessExitCode"
727 c_getProcessExitCode
728 :: PHANDLE
729 -> Ptr CInt
730 -> IO CInt
731
732 foreign import ccall interruptible "waitForProcess" -- NB. safe - can block
733 c_waitForProcess
734 :: PHANDLE
735 -> Ptr CInt
736 -> IO CInt
737
738
739 -- ----------------------------------------------------------------------------
740 -- Old deprecated variants
741 -- ----------------------------------------------------------------------------
742
743 -- TODO: We're not going to mark these functions as DEPRECATED immediately in
744 -- process-1.2.0.0. That's because some of their replacements have not been
745 -- around for all that long. But they should eventually be marked with a
746 -- suitable DEPRECATED pragma after a release or two.
747
748
749 -- ----------------------------------------------------------------------------
750 -- runCommand
751
752 --TODO: in a later release {-# DEPRECATED runCommand "Use 'spawnCommand' instead" #-}
753
754 {- | Runs a command using the shell.
755 -}
756 runCommand
757 :: String
758 -> IO ProcessHandle
759
760 runCommand string = do
761 (_,_,_,ph) <- createProcess_ "runCommand" (shell string)
762 return ph
763
764
765 -- ----------------------------------------------------------------------------
766 -- runProcess
767
768 --TODO: in a later release {-# DEPRECATED runProcess "Use 'spawnProcess' or 'createProcess' instead" #-}
769
770 {- | Runs a raw command, optionally specifying 'Handle's from which to
771 take the @stdin@, @stdout@ and @stderr@ channels for the new
772 process (otherwise these handles are inherited from the current
773 process).
774
775 Any 'Handle's passed to 'runProcess' are placed immediately in the
776 closed state.
777
778 Note: consider using the more general 'createProcess' instead of
779 'runProcess'.
780 -}
781 runProcess
782 :: FilePath -- ^ Filename of the executable (see 'RawCommand' for details)
783 -> [String] -- ^ Arguments to pass to the executable
784 -> Maybe FilePath -- ^ Optional path to the working directory
785 -> Maybe [(String,String)] -- ^ Optional environment (otherwise inherit)
786 -> Maybe Handle -- ^ Handle to use for @stdin@ (Nothing => use existing @stdin@)
787 -> Maybe Handle -- ^ Handle to use for @stdout@ (Nothing => use existing @stdout@)
788 -> Maybe Handle -- ^ Handle to use for @stderr@ (Nothing => use existing @stderr@)
789 -> IO ProcessHandle
790
791 runProcess cmd args mb_cwd mb_env mb_stdin mb_stdout mb_stderr = do
792 (_,_,_,ph) <-
793 createProcess_ "runProcess"
794 (proc cmd args){ cwd = mb_cwd,
795 env = mb_env,
796 std_in = mbToStd mb_stdin,
797 std_out = mbToStd mb_stdout,
798 std_err = mbToStd mb_stderr }
799 maybeClose mb_stdin
800 maybeClose mb_stdout
801 maybeClose mb_stderr
802 return ph
803 where
804 maybeClose :: Maybe Handle -> IO ()
805 maybeClose (Just hdl)
806 | hdl /= stdin && hdl /= stdout && hdl /= stderr = hClose hdl
807 maybeClose _ = return ()
808
809 mbToStd :: Maybe Handle -> StdStream
810 mbToStd Nothing = Inherit
811 mbToStd (Just hdl) = UseHandle hdl
812
813
814 -- ----------------------------------------------------------------------------
815 -- runInteractiveCommand
816
817 --TODO: in a later release {-# DEPRECATED runInteractiveCommand "Use 'createProcess' instead" #-}
818
819 {- | Runs a command using the shell, and returns 'Handle's that may
820 be used to communicate with the process via its @stdin@, @stdout@,
821 and @stderr@ respectively.
822 -}
823 runInteractiveCommand
824 :: String
825 -> IO (Handle,Handle,Handle,ProcessHandle)
826
827 runInteractiveCommand string =
828 runInteractiveProcess1 "runInteractiveCommand" (shell string)
829
830
831 -- ----------------------------------------------------------------------------
832 -- runInteractiveProcess
833
834 --TODO: in a later release {-# DEPRECATED runInteractiveCommand "Use 'createProcess' instead" #-}
835
836 {- | Runs a raw command, and returns 'Handle's that may be used to communicate
837 with the process via its @stdin@, @stdout@ and @stderr@ respectively.
838
839 For example, to start a process and feed a string to its stdin:
840
841 > (inp,out,err,pid) <- runInteractiveProcess "..."
842 > forkIO (hPutStr inp str)
843 -}
844 runInteractiveProcess
845 :: FilePath -- ^ Filename of the executable (see 'RawCommand' for details)
846 -> [String] -- ^ Arguments to pass to the executable
847 -> Maybe FilePath -- ^ Optional path to the working directory
848 -> Maybe [(String,String)] -- ^ Optional environment (otherwise inherit)
849 -> IO (Handle,Handle,Handle,ProcessHandle)
850
851 runInteractiveProcess cmd args mb_cwd mb_env = do
852 runInteractiveProcess1 "runInteractiveProcess"
853 (proc cmd args){ cwd = mb_cwd, env = mb_env }
854
855 runInteractiveProcess1
856 :: String
857 -> CreateProcess
858 -> IO (Handle,Handle,Handle,ProcessHandle)
859 runInteractiveProcess1 fun cmd = do
860 (mb_in, mb_out, mb_err, p) <-
861 createProcess_ fun
862 cmd{ std_in = CreatePipe,
863 std_out = CreatePipe,
864 std_err = CreatePipe }
865 return (fromJust mb_in, fromJust mb_out, fromJust mb_err, p)
866
867
868 -- ---------------------------------------------------------------------------
869 -- system & rawSystem
870
871 --TODO: in a later release {-# DEPRECATED system "Use 'callCommand' (or 'spawnCommand' and 'waitForProcess') instead" #-}
872
873 {-|
874 Computation @system cmd@ returns the exit code produced when the
875 operating system runs the shell command @cmd@.
876
877 This computation may fail with one of the following
878 'System.IO.Error.IOErrorType' exceptions:
879
880 [@PermissionDenied@]
881 The process has insufficient privileges to perform the operation.
882
883 [@ResourceExhausted@]
884 Insufficient resources are available to perform the operation.
885
886 [@UnsupportedOperation@]
887 The implementation does not support system calls.
888
889 On Windows, 'system' passes the command to the Windows command
890 interpreter (@CMD.EXE@ or @COMMAND.COM@), hence Unixy shell tricks
891 will not work.
892
893 On Unix systems, see 'waitForProcess' for the meaning of exit codes
894 when the process died as the result of a signal.
895 -}
896 system :: String -> IO ExitCode
897 system "" = ioException (ioeSetErrorString (mkIOError InvalidArgument "system" Nothing Nothing) "null command")
898 system str = do
899 (_,_,_,p) <- createProcess_ "system" (shell str) { delegate_ctlc = True }
900 waitForProcess p
901
902
903 --TODO: in a later release {-# DEPRECATED rawSystem "Use 'callProcess' (or 'spawnProcess' and 'waitForProcess') instead" #-}
904
905 {-|
906 The computation @'rawSystem' /cmd/ /args/@ runs the operating system command
907 @/cmd/@ in such a way that it receives as arguments the @/args/@ strings
908 exactly as given, with no funny escaping or shell meta-syntax expansion.
909 It will therefore behave more portably between operating systems than 'system'.
910
911 The return codes and possible failures are the same as for 'system'.
912 -}
913 rawSystem :: String -> [String] -> IO ExitCode
914 rawSystem cmd args = do
915 (_,_,_,p) <- createProcess_ "rawSystem" (proc cmd args) { delegate_ctlc = True }
916 waitForProcess p