/* $Copyright:	$
 * Copyright (c) 1984, 1985, 1986, 1987, 1988, 1989, 1990 
 * Sequent Computer Systems, Inc.   All rights reserved.
 *  
 * This software is furnished under a license and may be used
 * only in accordance with the terms of that license and with the
 * inclusion of the above copyright notice.   This software may not
 * be provided or otherwise made available to, or used by, any
 * other person.  No title to or ownership of the software is
 * hereby transferred.
 */

/* $Header: getpseudotty.c 1.1 89/01/26 $ */

#include <sys/types.h>
#include <sys/sysmacros.h>	/* for major(), minor() and makedev() */
#include <fcntl.h>
#include <sys/strpty.h>

extern char *dev_to_ttyname();

#define	GETPTY	"/dev/getpty"

/*
 * getpseudotty()
 * 	Allocate a pseudo tty pair
 *
 * Returns the fd associated with the master side.  Returns
 * -1 if no pseudo ports are available.  Also returns the 
 * name of both slave and master ports.
 */
int
getpseudotty(slave, master)
	char	**slave;
	char	**master;
{
	int	p;
	struct ptydev pdev;
	dev_t	mdev, sdev;
	char 	*mnamep, *snamep;

#define NAMELEN 25		/* 16 would be enough for "/dev/ttyAA/AAAA" */
	static char mname[NAMELEN];	/* overwritten on each call */
	static char sname[NAMELEN];	/* overwritten on each call */

	if ((p = open(GETPTY, O_RDWR)) < 0)
		return (-1);
	if (ioctl(p, TIOCPTYDEV, &pdev) < 0)
		return (-1);

#ifdef notdef
	printf("M maj %d min %d, S maj %d min %d\n",
	   pdev.ptym_major, pdev.ptym_minor, pdev.ptys_major, pdev.ptys_minor);
#endif
	/*
	 * Convert the master and slave dev_t into a file name
	 * and copy into a static place to return.
	 */
	mdev   = makedev((short)pdev.ptym_major, (short)pdev.ptym_minor);
	mnamep = dev_to_ttyname(mdev);
	(void) strncpy(mname, mnamep, NAMELEN);
	mname[NAMELEN-1] = '\0';	/* ensure null terminated */

	sdev   = makedev((short)pdev.ptys_major, (short)pdev.ptys_minor);
	snamep = dev_to_ttyname(sdev);
	(void) strncpy(sname, snamep, NAMELEN);
	sname[NAMELEN-1] = '\0';	/* ensure null terminated */

	*master = mname;
	*slave  = sname;
	return(p);
}
