Wait until SSH succeeds creating a port forwarding

I am calling ssh (OpenSSH) from a OSX/Linux-C++-Application via fork/exec to create a dynamic port forwarding. This is done using batch mode (-o BatchMode=yes) and a private key which is supplied to ssh (-i Option). The SSH call itself does not open a shell (-N Option).

This is my full SSH-Call:

ssh -N -D 9000 -o BatchMode=yes -i /path/to/private-key user@host

I would like to proceed with my application as soon as I can and so I have to find out if ssh succeeded creating the channel. SSH itself only returns if it has a problem.

Is there a possibility how I can detect a successful port forwarding?

Of course I can wait until the port is opened by SSH but I am looking for a more elegant solution. Another solution is to inspect SSH's Log (-v) waiting for "Entering interactive Session" but this sounds not very portable to me.


Solution 1:

Use the -f option and ssh will go into the background (i.e. fork and exit in the parent process), so you can just waitpid for the original ssh to finish and then you know (based on exit status) either that the connection failed or port forwarding is already setup.

Solution 2:

I think I found another (also hackish) solution. When starting SSH with

ssh -S /some/domain/socket -M ...args... host

it will create the control domain socket only it it succesfully established the connection. So I would have to wait for the domain socket to appear in the filesystem. Still not beautiful, but this sounds more robust than waiting for a network socket to appear.

Interestingly this can also be used to find out the PID of the Master (see R.. s Answer). Using

$ ssh -S /some/domain/socket -O check host
Master running (pid=25503)