Fixed: prevent closing psql process in the wrong order

It's the same bug than the commit b797717
Fixed: prevent looping indefinitely when stderr is EOF