Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15344131
  • 博文数量: 2005
  • 博客积分: 11986
  • 博客等级: 上将
  • 技术积分: 22535
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-17 13:56
文章分类

全部博文(2005)

文章存档

2014年(2)

2013年(2)

2012年(16)

2011年(66)

2010年(368)

2009年(743)

2008年(491)

2007年(317)

分类: LINUX

2008-09-01 15:12:44

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

阅读(6216) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~