Skip to content

Instantly share code, notes, and snippets.

@derekli66
Created October 23, 2022 06:44
Show Gist options
  • Save derekli66/470871f43cd24a561802326f6e78dd0f to your computer and use it in GitHub Desktop.
Save derekli66/470871f43cd24a561802326f6e78dd0f to your computer and use it in GitHub Desktop.
Sample code to use NSTask(Process) and NSPipe and NSRunloop
import Foundation
let task = Process()
// Set the launch tool path
task.launchPath = "/bin/sh"
// Set the command to run the task
let commandStr = "ls -l /Users/derek/PG"// "last | grep reboot"
var arguments = ["-c"]
arguments.append(commandStr)
task.arguments = arguments
// Set up the pipe to read the output data
let pipe = Pipe()
task.standardOutput = pipe
let fileHandle = pipe.fileHandleForReading
// Init a runloop flag to stop the current runloop
var passTheRunloop = false
// Register a notification to read the output data from the pipe
NotificationCenter.default.addObserver(forName: FileHandle.readCompletionNotification,
object: nil,
queue: .current) { notification in
let data = notification.userInfo?[NSFileHandleNotificationDataItem] as? Data ?? Data()
let log = String(data: data, encoding: .utf8)
print("\(log ?? "")")
// Terminate the runloop
passTheRunloop = true
}
do {
// Start the task
try task.run()
// Read the data output in the background for the reading file handle
fileHandle.readInBackgroundAndNotify()
} catch {
print("[DEBUG] Cannot process ls task for directory, /Users/derek/PG")
}
// Start the runloop and run until reaching the termination condition.
let runloop = RunLoop.current
while !passTheRunloop {
runloop.run(mode: .default, before: Date(timeInterval: 0.1, since: .now))
}
print("[DEBUG] Programm exists!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment