scoop:scoop.platform:0.1.0
src/process/child.scoop
Selected production source · src/process/child.scoop
1
package scoop.platform.process3
import scoop.map4
import scoop.platform.fs.*5
import scoop.platform.io.*6
import scoop.platform.system.*7
import scoop.time.Duration9
/**10
* Distinguishes normal process exit from signal termination.11
*/12
public 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)21
}23
/**24
* Collected stdout, stderr, and final status from process communication.25
*/26
public struct ProcessOutput(27
val stdout: Array<Byte>,28
val stderr: Array<Byte>,29
val status: ExitStatus30
)32
/**33
* An owned child process and any untaken pipe endpoints. Close closes retained pipes and waits for34
* termination; it does not automatically kill a running process.35
*/36
public class ChildProcess internal constructor(37
inputPipe: Boolean,38
outputPipe: Boolean,39
errorPipe: Boolean40
): Closeable {41
private var process: NativeProcessHandle = NativeProcessHandle(ULong.MAX_VALUE)42
private var result: ExitStatus? = None43
private var waitFailure: Throwable? = None44
private var closed: Boolean = false45
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
else51
None52
private var output: PipeSource? =53
if (outputPipe)54
Some(PipeSource(File.newOwner()))55
else56
None57
private var error: PipeSource? =58
if (errorPipe)59
Some(PipeSource(File.newOwner()))60
else61
None62
/**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() = closed79
internal fun adopt(pid: NativeProcessHandle, handles: MutableArray<NativeFileHandle>) {80
process = pid81
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 automatic88
* child cleanup.89
*/90
public fun takeStdin(): PipeSink? {91
val taken = input;92
input = None;93
return taken94
}95
/**96
* Transfers ownership of the child's output pipe to the caller and removes it from automatic97
* child cleanup.98
*/99
public fun takeStdout(): PipeSource? {100
val taken = output;101
output = None;102
return taken103
}104
/**105
* Transfers ownership of the child's error pipe to the caller and removes it from automatic106
* child cleanup.107
*/108
public fun takeStderr(): PipeSource? {109
val taken = error;110
error = None;111
return taken112
}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
@Unsafe143
{144
val observed =145
withProcess {146
pid -> @Unsafe147
{148
return@withProcess nativeWait(pid, noHang)149
}150
}151
val status = observed.status152
if (status == -2L)153
return None154
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 failure162
}163
process = NativeProcessHandle(ULong.MAX_VALUE)164
result =165
Some(166
if (operatingSystem == OperatingSystem.Windows || status < 256L)167
ExitStatus.Exited(status.toInt())168
else169
ExitStatus.Signaled((status - 256L).toInt())170
)171
}172
return result173
}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
return190
@Unsafe191
{192
val code =193
withProcess {194
pid -> @Unsafe195
{196
return@withProcess nativeSignal(pid, force)197
}198
}199
if (code != 0)200
failOperatingSystem(201
if (force)202
"kill"203
else204
"terminate",205
code206
)207
}208
}210
/**211
* Feeds optional input while draining stdout and stderr, then waits and returns their212
* 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 durations218
* 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 processes220
* 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 -> None247
}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 = failure267
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 reported278
}279
}281
/**282
* Closes retained pipe endpoints and waits for the child, preserving cleanup failures. Taken283
* endpoints remain the caller's responsibility.284
*/285
public override fun close() {286
if (closed)287
return288
if (active.load(MemoryOrder.Relaxed) != 0L)289
throw IllegalStateException(Some("process operation is active"))290
var failure: Throwable? = None291
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 = true303
}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
@Unsafe316
{317
nativeAbandon(process)318
}319
}320
}321
}323
internal fun combineProcessFailure(previous: Throwable?, next: Throwable): Throwable =324
when (previous) {325
case Some(val error) -> ResourceUseException(error, next)326
case None -> next327
}329
@Extern(name = "scoop_platform_process_wait")330
private fun nativeWait(process: NativeProcessHandle, noHang: Boolean): NativeProcessWait332
@Extern(name = "scoop_platform_process_signal")333
private fun nativeSignal(process: NativeProcessHandle, force: Boolean): Int335
@Extern(name = "scoop_platform_process_abandon")336
private fun nativeAbandon(process: NativeProcessHandle)