Last active
December 6, 2017 08:37
-
-
Save MiloszKrajewski/3c593ae65d4f7e0981bfdb337dd1d607 to your computer and use it in GitHub Desktop.
Simple process helper
This file contains hidden or 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
| #r "System.Management.dll" | |
| module Process = | |
| open System | |
| open System.Diagnostics | |
| open System.Threading.Tasks | |
| open System.Management | |
| let fix (proc: Process option) = | |
| match proc with | |
| | None -> None | |
| | Some p when p.HasExited -> None | |
| | _ -> proc | |
| let exec command = | |
| let comspec = Environment.GetEnvironmentVariable("COMSPEC") | |
| let arguments = command |> sprintf "/c %s" | |
| let info = ProcessStartInfo(comspec, arguments, UseShellExecute = false) | |
| Process.Start(info) | |
| let wait (proc: Process) = | |
| match proc with | |
| | p when p.HasExited -> Task.FromResult(0) :> Task | |
| | p -> Task.Factory.StartNew((fun () -> p.WaitForExit()), TaskCreationOptions.LongRunning) | |
| let private childrenW pid = | |
| let query = pid |> sprintf "select * from Win32_Process where ParentProcessID = %d" | |
| use searcher = new ManagementObjectSearcher(query) | |
| let collection = searcher.Get() |> Seq.cast<ManagementObject> | |
| collection |> Seq.map (fun o -> o.["ProcessId"] |> Convert.ToInt32 |> Process.GetProcessById) |> Seq.toArray | |
| let children (proc: Process) = | |
| match proc with | |
| | p when p.HasExited -> Seq.empty | |
| | p -> p.Id |> childrenW :> seq<_> | |
| let rec kill (proc: Process) = | |
| proc |> children |> Seq.iter kill | |
| proc.Kill() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment