5

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/.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Jeffrey Muller
  • 850
  • 1
  • 15
  • 28

2 Answers2

5

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.

Hibou57
  • 6,870
  • 6
  • 52
  • 56
4

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.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • Indeed, `posix_openpt` is portable (`/dev/ps/ptmx` is Linux specific, with no added value I know for it). The instructions sequence is: create a master with `posix_openpt`, then grant access to it with `grantpt` giving it the master as parameter, then unlock the pair with `unlockpt`, then get the file name of the slave to later open it with `ptsname`, then open the file name returned by `ptsname` with the usual `open`; all as described in POSIX 1. – Hibou57 Mar 28 '13 at 09:48
  • Here is more [words from POSIX about `ptmx`](http://pubs.opengroup.org/onlinepubs/009696899/functions/posix_openpt.html): “The standard developers considered the matter of adding a special device for cloning master pseudo-terminals: the /dev/ptmx device. However, consensus could not be reached, and it was felt that adding a new function would permit other implementations.” Also note how they considered `/dev/ptmx` instead of the Linux `/dev/ps/ptmx` – Hibou57 Mar 29 '13 at 12:22