Here a simple Swift code for a macOS console app:
import Foundation
print("hello world")
RunLoop.main.run()
In my real code, I use RunLoop
to avoid leaving the console app, because I react to some CoreBluetooth events and have an infinite loop of things I want to display. I just want to quit the app using Ctrl+C.
However, when using RunLoop.main.run()
I cannot grep the output any more in my terminal:
$ ./app
hello world
^C
$ ./app | grep hello
^C
Some ideas about how I can grep the output?
I guess the usage of RunLoop
is a bad idea, but what can be the alternative without having a kind of active wait or manually manage some execution threads?
You could try to either flush stdout:
fflush(__stdoutp)
or set the buffer size on stdout to zero (makes it fast, but using more resources):
setbuf(__stdoutp, nil)
See Swift: how to flush stdout after println?
This is typically the solution, when you see output to the terminal, but no output once you pipe the process into another one, like grep. The piping affects the default choice for buffering. Hope this helps!