fixes for PTY handling

This should fix #3877.

All credit for the patch goes to @cayblood; I just tested to confirm it works and opened it as a PR.