Finding a stream's filename

michael.p.lindner mpl at cbnewsl.ATT.COM
Fri Jul 28 07:11:08 AEST 1989


In article <440 at uop.uop.EDU>, nsayer at 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;
}



More information about the Comp.unix.questions mailing list