Created
August 1, 2021 23:56
-
-
Save moutend/4b554d7cb59aa63dd302621a4196cf6e to your computer and use it in GitHub Desktop.
This file contains 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
import Foundation | |
import Darwin | |
class A: NSObject { | |
var task = Process() | |
var slaveFile: FileHandle? | |
var masterFile: FileHandle? | |
override init() { | |
let masterFD = posix_openpt(O_RDWR) | |
grantpt(masterFD) | |
unlockpt(masterFD) | |
self.masterFile = FileHandle.init(fileDescriptor: masterFD) | |
let slavePath = String.init(cString: ptsname(masterFD)) | |
self.slaveFile = FileHandle.init(forUpdatingAtPath: slavePath) | |
self.task.executableURL = URL(fileURLWithPath: "/bin/bash") | |
self.task.arguments = ["-i"] | |
self.task.standardOutput = slaveFile | |
self.task.standardInput = slaveFile | |
self.task.standardError = slaveFile | |
} | |
func run() { | |
DispatchQueue.global(qos: .userInitiated).async { [weak self] in | |
guard let self = self else { | |
return | |
} | |
do { | |
try self.task.run() | |
} catch { | |
fatalError("failed to start task: \(error)") | |
} | |
} | |
let data1 = self.masterFile!.availableData | |
let output1 = String(data: data1, encoding: String.Encoding.utf8)! | |
print("Output: \(output1)") | |
self.masterFile!.write("echo $HOME\u{0d}".data(using: String.Encoding.utf8)!) | |
sleep(2) | |
let data2 = self.masterFile!.availableData | |
let output2 = String(data: data2, encoding: String.Encoding.utf8)! | |
print("Output: \(output2)") | |
} | |
} | |
let a = A() | |
a.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment