我正在尝试使用伪终端编写一个可以使用密码登录 SSH 的应用程序。但是如果我 write() 到主设备,那么数据就不会出现在从设备中。这是一个简单的测试用例:
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#ifdef __linux__
#include <pty.h>
#else
#include <util.h>
#endif
int
main() {
int master;
pid_t pid = forkpty(&master, NULL, NULL, NULL);
if (pid == 0) {
int ch;
read(0, &ch, 1);
_exit(1);
} else {
printf("Press Enter to send a byte.\n");
getchar();
write(master, "1", 1);
printf("Done. Waiting for process to exit...\n");
waitpid(pid, NULL, 0);
return 0;
}
}
该应用程序将首先输出“Press Enter to send a byte”。按 Enter 后,我希望子进程的 read() 返回。但是即使 master 的 write() 成功,那里的 read() 似乎也会无限期地阻塞,所以 master 在 waitpid() 上永远等待。这是怎么回事?