Make dns-sd exit after listing service
Solution 1:
It’s designed to not exit. We have to track the process and send it an exit / kill signal. Apple even calls this out in the manual page. (and worse, doesn't supply bindings for dns-sd in swift or any other language that I can find so that pert is an exercise left for the reader…)
For example, calls like "browse" never complete; the action of performing a "browse" sets in motion machinery to notify the client whenever instances of that service type appear or disappear from the network. These notifications continue to be delivered indefinitely, for minutes, hours, or even days, as services come and go, until the client explicitly terminates the call.
The best I can do for scripting is use expect
to fork the process with a timeout or just use something brute force like backgrounding the command so I can sleep and kill it and copy the results to pasteboard.
dns-sd -B _home-sharing &
sleep 5 && kill %1
If you have another background process as %1
, this will kill the wrong process.
In practice, I've never had to wait more than 30 seconds for a good browse or listen but not all networks are the same size.