For just an update. I guess that the terminal gets hanged because of the tcdrain(fd) command . I tried it by modifying some part of the code. Please help.