I'm a little confused about what the body of the function is supposed to consist of because you are referencing code from your previous example. Could you help me out by posting the fully self-contained function that I can use?
Right now, I am able to type text into my terminal, (previously readLine would immediately return nil) but when I press enter, the function does not return.
Here's what I have:
func withReadLine(_ body: () -> Void) {
// most of the code like before
let oldStdin = dup(STDIN_FILENO)
let ttyFD = open("/dev/tty", O_RDONLY)
if ttyFD == -1 {
fatalError("withReadLine: couldn't read line")
}
dup2(ttyFD, STDIN_FILENO)
defer {
// Restore the original stdin
dup2(oldStdin, STDIN_FILENO)
// Close our copy of the original stdin.
close(oldStdin)
}
// Run the code.
body()
}
// example:
print("What is your name?", terminator: " ")
withReadLine {
let name = readLine()
print("your name is \(name ?? "nil")")
}