C Fork一个新的tty
我必须在不使用 forkpty() 的情况下创建一对新的 tty(主和从)。
在 man of pts(4) 中写道:
当进程打开/dev/ptmx时,它会获取伪终端主设备(PTM)的文件描述符,并在/dev/pts目录中创建伪终端从设备(PTS)。
使用 C 语言的一个小程序,我像这样打开 /dev/ptmx :
open("/dev/ptmx", O_RDWR);
但是 /dev/pts/ 中没有创建新的 pty。
I have to create a new pair of tty (master and slave) without using forkpty().
In the man of pts(4), it is written that :
When a process opens /dev/ptmx, it gets a file descriptor for a pseudo-terminal master (PTM), and a pseudo-terminal slave (PTS) device is created in the /dev/pts directory.
With a little program in C, I open /dev/ptmx like that :
open("/dev/ptmx", O_RDWR);
But there is no new pty created in /dev/pts/.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是关于该主题的一个很好的教程:使用伪终端来控制交互式程序, pty,pdip。如果此链接以错误 403 结束,则这是另一个错误: http://rkoucha.fr/tech_corner/ pty_pdip.html
特别是,请查看页面中间标题“通过伪终端进行进程间通信”下的示例源代码。这是一个进程自行分叉的示例,然后两个进程通过父进程先前打开的 PTY 相互通信。
Here is a good tutorial on the topic: Using pseudo-terminals to control interactive programs, pty, pdip. It this link ends in an error 403, here is another one: http://rkoucha.fr/tech_corner/pty_pdip.html
Particularly, look at the sample source at the middle of the page, under title “Inter-process communication through a pseudo-terminal”. That's an example of a process which fork it‑self, then the two processes communicate each‑others via a PTY the parent process priorly opened.
要实际创建可用的 pty 对,还必须对 open 调用返回的 fd 调用 grantpt(3) 和unlockpt(3)。它没有明确定义在该过程中文件系统中实际从属 pty 文件节点的创建位置 - 某些系统(通常 /dev/pts 是特殊文件系统的系统)将在打开时创建它,而其他系统将创建它它作为 grantpt 或unlockpt 调用的一部分。它也不能保证从属设备将位于 /dev/pts 中——它可能在其他地方——所以您需要调用 ptsname(3) 来找出它在哪里。
调用 posix_openpt(3) 而不是直接打开也可能稍微更便携。
To actually create a usable pty pair, you must also call grantpt(3) and unlockpt(3) on the fd returned by the open call. Its not well-defined exactly where in that process the actual slave pty file node in the filesystem is created -- some systems (those where /dev/pts is a special filesystem, usually) will create it on the open, while others will create it as part of the grantpt or unlockpt call. Its also not guarenteed that the slave will be in /dev/pts -- it might be somewhere else -- so you need to call ptsname(3) to find out where it is.
It also may be slightly more portable to call posix_openpt(3) rather than open directly.