免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2481 | 回复: 0
打印 上一主题 下一主题

浅析ptmx代码级open如何运作ptyp,ttyp,pts伪终端(转载) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-02-19 20:37 |只看该作者 |倒序浏览

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


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/92631/showart_1834791.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP