Scoop API

scoop:scoop.platform:0.1.0

src/process/communication.scoop

Selected production source · src/process/communication.scoop

1package scoop.platform.process
3import scoop.platform.time.MonotonicTimeSource
4import scoop.platform.time.elapsedNow
5import scoop.platform.time.sleep
6import scoop.time.Duration
8/**
9 * The communication deadline expired. The arrays contain bytes received before cleanup completed;
10 * unread pipe data is not included. The owned child has been killed and reaped unless cleanup also
11 * failed, in which case ResourceUseException retains this exception and the cleanup error.
12 */
13public class ProcessTimeoutException public constructor(
14 /**
15 * Bytes collected from the child's standard output.
16 */
17 public val stdout: Array<Byte>,
18 /**
19 * Bytes collected from the child's standard error.
20 */
21 public val stderr: Array<Byte>
22): Exception(Some("process communication timed out"))
24internal class ProcessDeadline internal constructor(private val timeout: Duration) {
25 private val start = MonotonicTimeSource.markNow()
27 internal fun remaining(): Duration {
28 val elapsed = start.elapsedNow()
29 return if (elapsed >= timeout)
30 Duration.ZERO
31 else
32 timeout - elapsed
33 }
35 internal fun milliseconds(): Int {
36 val left = remaining()
37 if (left.floorSeconds > 2147483L)
38 return Int.MAX_VALUE
39 val milliseconds =
40 left.floorSeconds * 1000L + (left.nanosecondsOfSecond.toLong() + 999999L) / 1000000L
41 return if (milliseconds > Int.MAX_VALUE.toLong())
42 Int.MAX_VALUE
43 else
44 milliseconds.toInt()
45 }
48internal fun ChildProcess.waitForCommunication(deadline: ProcessDeadline?): ExitStatus? {
49 val limit =
50 when (deadline) {
51 case None -> return Some(wait())
52 case Some(val value) -> value
53 }
54 while (true) {
55 val status = tryWait()
56 if (status != None)
57 return status
58 val remaining = limit.remaining()
59 if (remaining == Duration.ZERO)
60 return None
61 // No portable process-completion fd exists on every supported POSIX host.
62 sleep(
63 if (remaining < Duration.milliseconds(10L))
64 remaining
65 else
66 Duration.milliseconds(10L)
67 )
68 }