home *** CD-ROM | disk | FTP | other *** search
/ Super Net 1 / SUPERNET_1.iso / PC / OTROS / UNIX / ARCHIE / CLIENTS / NEXTARCH / PTY.C < prev    next >
Encoding:
C/C++ Source or Header  |  1992-01-18  |  2.0 KB  |  79 lines

  1. /*
  2.  * Pseudo-terminal routines for 4.3BSD.
  3.  */
  4.  
  5. #include    <sys/types.h>
  6. #include    <sys/stat.h>
  7. #include    <sys/file.h>
  8. #include <strings.h>
  9. #include <libc.h>
  10.  
  11. /*
  12.  * The name of the pty master device is stored here by pty_master().
  13.  * The next call to pty_slave() uses this name for the slave.
  14.  */
  15.  
  16. static char    pty_name[12];    /* "/dev/[pt]tyXY" = 10 chars + null byte */
  17.  
  18. int            /* returns the file descriptor, or -1 on error */
  19. pty_master()
  20. {
  21.     int        i, master_fd;
  22.     char        *ptr;
  23.     struct stat    statbuff;
  24.     static char    ptychar[] = "pqrs";            /* X */
  25.     static char    hexdigit[] = "0123456789abcdef";    /* Y */
  26.  
  27.     /*
  28.      * Open the master half - "/dev/pty[pqrs][0-9a-f]".
  29.      * There is no easy way to obtain an available minor device
  30.      * (similar to a streams clone open) - we have to try them
  31.      * all until we find an unused one.
  32.      */
  33.  
  34.     for (ptr = ptychar; *ptr != 0; ptr++) {
  35.         strcpy(pty_name, "/dev/ptyXY");
  36.         pty_name[8] = *ptr;    /* X */
  37.         pty_name[9] = '0';    /* Y */
  38.  
  39.         /*
  40.          * If this name, "/dev/ptyX0" doesn't even exist,
  41.          * then we can quit now.  It means the system doesn't
  42.          * have /dev entries for this group of 16 ptys.
  43.          */
  44.  
  45.         if (stat(pty_name, &statbuff) < 0)
  46.             break;
  47.  
  48.         for (i = 0; i < 16; i++) {
  49.             pty_name[9] = hexdigit[i];    /* 0-15 -> 0-9a-f */
  50.             if ( (master_fd = open(pty_name, O_RDWR)) >= 0)
  51.                 return(master_fd);    /* got it, done */
  52.         }
  53.     }
  54.     return(-1);    /* couldn't open master, assume all pty's are in use */
  55. }
  56.  
  57. /*
  58.  * Open the slave half of a pseudo-terminal.
  59.  * Note that the master half of a pty is a single-open device,
  60.  * so there isn't a race condition between opening the master
  61.  * above and opening the slave below.  The only way the slave
  62.  * open will fail is if someone has opened the slave without
  63.  * first opening the master.
  64.  */
  65.  
  66. int            /* returns the file descriptor, or -1 on error */
  67. pty_slave(int master_fd)
  68. {
  69.     int    slave_fd;
  70.  
  71.     pty_name[5] = 't';    /* change "/dev/ptyXY" to "/dev/ttyXY" */
  72.     if ( (slave_fd = open(pty_name, O_RDWR)) < 0) {
  73.         close(master_fd);
  74.         return(-1);
  75.     }
  76.  
  77.     return(slave_fd);
  78. }
  79.