浅析ptmx代码级open如何运作ptyp,ttyp,pts伪终端(转载)

1.对ptmx执行open操作,将创建1对tty主从设备.
tty_init
=>cdev_init(&ptmx_cdev, &ptmx_fops);
=>然后创建/dev/ptmx节点[luther.gliethttp].
所以/dev/ptmx节点的open函数为ptmx_fops.ptmx_open()
static int ptmx_open(struct inode * inode, struct file * filp)
{
    ...
    idr_ret = idr_get_new(&allocated_ptys, NULL, &index);
    ...
    if (index >= pty_limit) {//NR_UNIX98_PTY_DEFAULT也就是4096个
        ...
    }
    ...
    mutex_lock(&tty_mutex);
    retval = init_dev(ptm_driver, index, &tty);//以index为pts的设备索引号,创建成对的主从设备ptmx和pts
    mutex_unlock(&tty_mutex);
    ...
    retval = ptm_driver->open(tty, filp);
    ...
}
所以fdm = open("/dev/ptmx", O_RDWR);操作之后,将产生一个成对的ptyp和ttyp主从tty设备,并返回ptyp主设备句柄.
2.调用ioctl获得与fdm主设备配对的ttyp设备号.
tty_ioctl
=>tty->driver->ioctl
=>在unix98_pty_init(),仅仅对ptmx主设备赋予了ioctl操作:ptm_driver->ioctl =pty_unix98_ioctl;
=>pty_unix98_ioctl
=>
static int pty_unix98_ioctl(struct tty_struct *tty, struct file *file,
             unsigned int cmd, unsigned long arg)
{
    switch (cmd) {
    case TIOCSPTLCK: /* Set PT Lock (disallow slave open) */
        return pty_set_lock(tty, (int __user *)arg);
    case TIOCGPTN: /* Get PT Number */
        return put_user(tty->index, (unsigned int __user *)arg);//当前tty对应的为ptmx结构,它的index就是与之配对的pts
    }

    return -ENOIOCTLCMD;
}
3.看看glibc库中如何封装ptsname函数,如下为精简版[luther.gliethttp].
char* ptsname( int fd )
{
    unsigned int pty_num;
    static char buff[64];

    if ( ioctl( fd, TIOCGPTN, &pty_num ) != 0 )//最终调用上面的pty_unix98_ioctl获取当前ptmx主设备对应的pty从设备号.
        return NULL;

    snprintf( buff, sizeof(buff), "/dev/pts/%u", pty_num );//格式化为/dev/pts/0,/dev/pts/1等,即:pts对应的文件全路径.
    return buff;
}
4.应用实例
   int fdm fds;
   char *slavename;
   extern char *ptsname();
   
    fdm = open("/dev/ptmx", O_RDWR); /* open master */
    grantpt(fdm); /* change permission of slave */
    unlockpt(fdm); /* unlock slave */
    slavename = ptsname(fdm); /* get name of slave */
    fds = open(slavename, O_RDWR); /* open slave */
    ioctl(fds, I_PUSH, "ptem"); /* push ptem */
    ioctl(fds, I_PUSH, "ldterm"); /* push ldterm */

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值