Scoop API

scoop:scoop.platform:0.1.0

src/process/child.scoop

Selected production source · src/process/child.scoop

1package scoop.platform.process
3import scoop.map
4import scoop.platform.fs.*
5import scoop.platform.io.*
6import scoop.platform.system.*
7import scoop.time.Duration
9/**
10 * Distinguishes normal process exit from signal termination.
11 */
12public enum ExitStatus {
13 /**
14 * The process exited with this status code.
15 */
16 Exited(val code: Int),
17 /**
18 * The process terminated because of this native signal.
19 */
20 Signaled(val signal: Int)
23/**
24 * Collected stdout, stderr, and final status from process communication.
25 */
26public struct ProcessOutput(
27 val stdout: Array<Byte>,
28 val stderr: Array<Byte>,
29 val status: ExitStatus
32/**
33 * An owned child process and any untaken pipe endpoints. Close closes retained pipes and waits for
34 * termination; it does not automatically kill a running process.
35 */
36public class ChildProcess internal constructor(
37 inputPipe: Boolean,
38 outputPipe: Boolean,
39 errorPipe: Boolean
40): Closeable {
41 private var process: NativeProcessHandle = NativeProcessHandle(ULong.MAX_VALUE)
42 private var result: ExitStatus? = None
43 private var waitFailure: Throwable? = None
44 private var closed: Boolean = false
45 private val active: AtomicLong = AtomicLong(0L)
46 private val configured: Array<Boolean> = [inputPipe, outputPipe, errorPipe]
47 private var input: PipeSink? =
48 if (inputPipe)
49 Some(PipeSink(File.newOwner()))
50 else
51 None
52 private var output: PipeSource? =
53 if (outputPipe)
54 Some(PipeSource(File.newOwner()))
55 else
56 None
57 private var error: PipeSource? =
58 if (errorPipe)
59 Some(PipeSource(File.newOwner()))
60 else
61 None
62 /**
63 * A borrowed view of the child's input pipe, or None when it is not available.
64 */
65 public val stdin: ByteSink? get() = input?.borrowed()
66 /**
67 * A borrowed view of the child's output pipe, or None when it is not available.
68 */
69 public val stdout: ByteSource? get() = output?.borrowed()
70 /**
71 * A borrowed view of the child's error pipe, or None when it is not available.
72 */
73 public val stderr: ByteSource? get() = error?.borrowed()
74 /**
75 * Whether this owned resource has been closed.
76 */
77 public val isClosed: Boolean get() = closed
79 internal fun adopt(pid: NativeProcessHandle, handles: MutableArray<NativeFileHandle>) {
80 process = pid
81 input?.file?.adoptHandle(handles[0L])
82 output?.file?.adoptHandle(handles[1L])
83 error?.file?.adoptHandle(handles[2L])
84 }
86 /**
87 * Transfers ownership of the child's input pipe to the caller and removes it from automatic
88 * child cleanup.
89 */
90 public fun takeStdin(): PipeSink? {
91 val taken = input;
92 input = None;
93 return taken
94 }
95 /**
96 * Transfers ownership of the child's output pipe to the caller and removes it from automatic
97 * child cleanup.
98 */
99 public fun takeStdout(): PipeSource? {
100 val taken = output;
101 output = None;
102 return taken
103 }
104 /**
105 * Transfers ownership of the child's error pipe to the caller and removes it from automatic
106 * child cleanup.
107 */
108 public fun takeStderr(): PipeSource? {
109 val taken = error;
110 error = None;
111 return taken
112 }
114 /**
115 * Waits for termination and returns the final status.
116 */
117 public fun wait(): ExitStatus = observe(false)!!
118 /**
119 * Returns a final status if available, or None while the child is still running.
120 */
121 public fun tryWait(): ExitStatus? = observe(true)
123 private fun <R> withProcess(block: (NativeProcessHandle) -> R): R {
124 active.fetchAdd(1L, MemoryOrder.Relaxed)
125 try {
126 return block(process)
127 }
128 finally {
129 active.fetchSub(1L, MemoryOrder.Relaxed)
130 }
131 }
133 private fun observe(noHang: Boolean): ExitStatus? {
134 when (waitFailure) {
135 case Some(val failure) -> throw failure;
136 case None -> {}
137 }
138 when (result) {
139 case Some(_) -> return result;
140 case None -> {}
141 }
142 @Unsafe
143 {
144 val observed =
145 withProcess {
146 pid -> @Unsafe
147 {
148 return@withProcess nativeWait(pid, noHang)
149 }
150 }
151 val status = observed.status
152 if (status == -2L)
153 return None
154 if (status < 0L) {
155 val error = processError(observed.error)
156 val failure = PlatformException("wait", error.kind, Some(error))
157 if (status == -3L) {
158 process = NativeProcessHandle(ULong.MAX_VALUE);
159 waitFailure = Some(failure)
160 }
161 throw failure
162 }
163 process = NativeProcessHandle(ULong.MAX_VALUE)
164 result =
165 Some(
166 if (operatingSystem == OperatingSystem.Windows || status < 256L)
167 ExitStatus.Exited(status.toInt())
168 else
169 ExitStatus.Signaled((status - 256L).toInt())
170 )
171 }
172 return result
173 }
175 /**
176 * Requests SIGTERM on POSIX or TerminateProcess with exit code 1 on Windows.
177 */
178 public fun terminate() {
179 signal(false)
180 }
181 /**
182 * Requests forced process termination.
183 */
184 public fun kill() {
185 signal(true)
186 }
187 private fun signal(force: Boolean) {
188 if (process.value == ULong.MAX_VALUE)
189 return
190 @Unsafe
191 {
192 val code =
193 withProcess {
194 pid -> @Unsafe
195 {
196 return@withProcess nativeSignal(pid, force)
197 }
198 }
199 if (code != 0)
200 failOperatingSystem(
201 if (force)
202 "kill"
203 else
204 "terminate",
205 code
206 )
207 }
208 }
210 /**
211 * Feeds optional input while draining stdout and stderr, then waits and returns their
212 * collected bytes and status.
213 */
214 public fun communicate(input: List<Byte>? = None): ProcessOutput = communicateWith(input, None)
216 /**
217 * Uses one monotonic timeout for input, both outputs, and process exit. Negative durations
218 * leave the pipes untouched. On timeout, closes the pipes, kills and reaps the owned child,
219 * and throws ProcessTimeoutException with the bytes collected so far. Descendant processes
220 * are not managed. Cleanup and OS scheduling can delay return beyond the timeout.
221 */
222 public fun communicate(timeout: Duration, input: List<Byte>? = None): ProcessOutput {
223 if (timeout.floorSeconds < 0L)
224 throw IllegalArgumentException(Some("negative process communication timeout"))
225 return communicateWith(input, Some(timeout))
226 }
228 private fun communicateWith(input: List<Byte>?, timeout: Duration?): ProcessOutput {
229 if (closed)
230 throw IllegalStateException(Some("process is closed"))
231 when (input) {
232 case Some(_) -> if (!configured[0L])
233 throw IllegalArgumentException(Some("input requires stdin pipe"))
234 case None -> {}
235 }
236 if (
237 (configured[0L] && (this.input?.isClosed ?: true)) ||
238 (configured[1L] && (output?.isClosed ?: true)) ||
239 (configured[2L] && (error?.isClosed ?: true))
240 ) {
241 throw IllegalStateException(Some("process pipe was already taken or closed"))
242 }
243 val snapshot: Array<Byte>? =
244 when (input) {
245 case Some(val bytes) -> Some(bytes.toArray())
246 case None -> None
247 }
248 val deadline = timeout.map { ProcessDeadline(it) }
249 val sink = takeStdin()
250 val source = takeStdout()
251 val errors = takeStderr()
252 val terminationRequested = AtomicBoolean(false)
253 val abort: () -> Unit =
254 {
255 if (terminationRequested.compareAndSet(false, true)) {
256 kill()
257 }
258 }
259 try {
260 val(stdout, stderr) = transferPipes(sink, source, errors, snapshot, deadline, abort)
261 val status = waitForCommunication(deadline)
262 if (status == None)
263 throw ProcessTimeoutException(stdout, stderr)
264 return ProcessOutput(stdout, stderr, status!!)
265 } catch (failure: Throwable) {
266 var reported = failure
267 try {
268 abort()
269 } catch (cleanup: Throwable) {
270 reported = ResourceUseException(reported, cleanup)
271 }
272 try {
273 wait()
274 } catch (cleanup: Throwable) {
275 reported = ResourceUseException(reported, cleanup)
276 }
277 throw reported
278 }
279 }
281 /**
282 * Closes retained pipe endpoints and waits for the child, preserving cleanup failures. Taken
283 * endpoints remain the caller's responsibility.
284 */
285 public override fun close() {
286 if (closed)
287 return
288 if (active.load(MemoryOrder.Relaxed) != 0L)
289 throw IllegalStateException(Some("process operation is active"))
290 var failure: Throwable? = None
291 val endpoints: Array<File?> = [takeStdin()?.file, takeStdout()?.file, takeStderr()?.file]
292 for (endpoint in endpoints) {
293 try {
294 endpoint?.close()
295 }
296 catch (error: Throwable) {
297 failure = Some(combineProcessFailure(failure, error))
298 }
299 }
300 try {
301 wait();
302 closed = true
303 }
304 catch (error: Throwable) {
305 failure = Some(combineProcessFailure(failure, error))
306 }
307 when (failure) {
308 case Some(val error) -> throw error;
309 case None -> {}
310 }
311 }
313 release {
314 if (process.value != ULong.MAX_VALUE) {
315 @Unsafe
316 {
317 nativeAbandon(process)
318 }
319 }
320 }
323internal fun combineProcessFailure(previous: Throwable?, next: Throwable): Throwable =
324 when (previous) {
325 case Some(val error) -> ResourceUseException(error, next)
326 case None -> next
327 }
329@Extern(name = "scoop_platform_process_wait")
330private fun nativeWait(process: NativeProcessHandle, noHang: Boolean): NativeProcessWait
332@Extern(name = "scoop_platform_process_signal")
333private fun nativeSignal(process: NativeProcessHandle, force: Boolean): Int
335@Extern(name = "scoop_platform_process_abandon")
336private fun nativeAbandon(process: NativeProcessHandle)