cpcnw abandoning GNU Grep and using native awk as in rvp's example fixes the issue completely.
I doubt if if using awk instead of GNU grep was what's responsible. As I said before, your original pipeline had races. There is really a strict ordering required here: xwininfo has to run first; then xdotool has to provide the click to select the window. This is what I've done by first starting xdotool with a delay in the background. The shell then starts the xwininfo pipeline immediately afterwards, and this whole thing then waits for xdotool to provide the click.
Just try your original pipeline repeatedly on its own to see it failing some of the time:
$ xdotool click 1 | xwininfo | awk '/id: / { print $4 }'
0xe0000c
$ xdotool click 1 | xwininfo | awk '/id: / { print $4 }'
0xe0000c
$ xdotool click 1 | xwininfo | awk '/id: / { print $4 }'
xwininfo: error: Can't grab the mouse.
In any case, this method of selecting windows is quite silly (and still potentially racy--on very slow machines). Hacking twm to provide
f.exec "cmd args %w"
to substitute the window-ID for %w shouldn't be that hard methinks.