Chinaunix首页 | 论坛 | 博客
  • 博客访问: 967203
  • 博文数量: 403
  • 博客积分: 27
  • 博客等级: 民兵
  • 技术积分: 165
  • 用 户 组: 普通用户
  • 注册时间: 2011-12-25 22:20
文章分类

全部博文(403)

文章存档

2016年(3)

2015年(16)

2014年(163)

2013年(222)

分类: LINUX

2013-12-16 17:07:39

浅析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 */

阅读(739) | 评论(0) | 转发(0) |
0

上一篇:Linux下tty/pty/pts/ptmx详解(转)

下一篇:TIPC

给主人留下些什么吧!~~