[comp.unix.questions] Finding a stream's filename

nsayer@uop.EDU (Nick Sayer) (07/26/89)

I am in the midst of writing a new getty for a terribly ancient
machine, whose init passes getty only a single character, from which
it is to divine all the terminal data.

Trouble is, I want this getty to look at the uucp lock files to see
if uucp wants to use the phone. getty can't figure out the filename
of the lock file, because getty doesn't know what terminal it's
running on!

Can a process either 1) find the filename associated with an fopened
or opened file (and then then let me do it on stdout) or 2) find
out what device it's running on (less nice).

---------------------------------------------------------------------
Nick Sayer | ...{ apple!cheers | pacbell!cogent }!quack!mrapple
... or cheers!quack!mrapple@apple.COM
Packet radio: N6QQQ @ WB6V | FredMail: NSAYER@MADERA%NORCAL
Disclaimer: The BBC would like to appologise for that announcement
Note: Use this address. I don't have news running on quack, but mail works

mpl@cbnewsl.ATT.COM (michael.p.lindner) (07/28/89)

In article <440@uop.uop.EDU>, nsayer@uop.EDU (Nick Sayer) writes:
> Can a process either 1) find the filename associated with an fopened
> or opened file (and then then let me do it on stdout) or 2) find
> out what device it's running on (less nice).
> 
> ---------------------------------------------------------------------
> Nick Sayer | ...{ apple!cheers | pacbell!cogent }!quack!mrapple

It can be done.  Do an fstat(2) on the file descriptor of interest.  That
gives you the inode number.  Then open /dev/ and read the entries until
you find the matching inode number.

Mike Lindner
attunix!mpl
AT&T Bell Laboratories
190 River Rd.
Summit, NJ 07901

#include	<sys/types.h>
#include	<sys/stat.h>
#include	<sys/dir.h>

char *
find_tty()
{
	static char	name[DIRSIZ + 1];
	int	fd;
	struct stat	sbuf;
	struct direct	dbuf;

	if (fstat(1, &sbuf)) {
		/* something has gone wrong */
		perror("fstat of stdout");
		exit(1);
	}
	if ((fd = open("/dev", 0)) < 0) {
		perror("open of /dev");
		exit(1);
	}
	name[0] = '\0';
	while (read(fd, &dbuf, sizeof(dbuf)) == sizeof(dbuf)) {
		if (dbuf.d_ino == sbuf.st_ino) {
			strncpy(name, dbuf.d_name, DIRSIZ);
			name[DIRSIZ] = '\0';
			break;
		}
	}
	close(fd);
	return name;
}

guy@auspex.auspex.com (Guy Harris) (07/29/89)

>It can be done.  Do an fstat(2) on the file descriptor of interest.  That
>gives you the inode number.  Then open /dev/ and read the entries until
>you find the matching inode number.

Or, better yet, just use the "ttyname" routine (see TTYNAME(3) or
TTYNAME(3C)), if the descriptor is open to a terminal; this saves you
the trouble of reinventing said routine.