Wait for forked process to open a window

processscriptingsuckless-terminalwindowx11

I'm trying to make a script like the following:

st -n dropdown &
pid=$(xdotool search --classname dropdown)

st is a terminal emulator

I'm trying to run some commands on the created st using xdotool. Unfortunately the commands after st -n dropdown & are run before the actual st terminal starts up so there is no pid. I can always just put sleep 0.1 after but there are instances (on older machines for example) where it will take longer than 0.1 seconds for the terminal to start. Is there a way to wait for the terminal to start before executing the rest of the script?

The wait command doesn't work because it waits for the process to finish, which in the case of st is when it is killed which is not what I want.

Best Answer

xtoolwait is a utility that launches an X application and waits until it has mapped its window. It then returns control to the original shell session.

It is usually used from one's .xinitrc or .xsession file.

You may use it in your script like this:

xtoolwait st -n dropdown
pid=$(xdotool search --classname dropdown)

The second command will not start executing until xtoolwait detects that st has mapped its window. Note the lack of & on the first line (it's not needed). This may offer enough delay for the second command to find the PID correctly.