1ae901935SOliver Tappe/*
2e701d86aSIngo Weinhold * Copyright 2003, Daniel Reinhold, danielre@users.sf.net. All rights reserved.
3e701d86aSIngo Weinhold * Copyright 2007, Fran��ois Revol, mmu_man@users.sf.net. All rights reserved.
4e701d86aSIngo Weinhold * Distributed under the terms of the MIT License.
5e701d86aSIngo Weinhold */
6f2912266SDaniel Reinhold
7ea2aba5dSAxel Dörfler
8ea2aba5dSAxel Dörfler#include <SupportDefs.h>
9158a9c38SFrançois Revol#include <Drivers.h>
10ea2aba5dSAxel Dörfler
11158a9c38SFrançois Revol#include <errno.h>
12f2912266SDaniel Reinhold#include <stdio.h>
13f2912266SDaniel Reinhold#include <string.h>
14f2912266SDaniel Reinhold#include <unistd.h>
15f2912266SDaniel Reinhold#include <sys/stat.h>
16e9004ce2Sshatty#include <sys/param.h>
17f2912266SDaniel Reinhold
18ae901935SOliver Tappe#include <errno_private.h>
19ae901935SOliver Tappe
20ae901935SOliver Tappe
21158a9c38SFrançois Revol/**
22158a9c38SFrançois Revol * give the name of a tty fd. threadsafe.
23158a9c38SFrançois Revol * @param fd the tty to get the name from.
24158a9c38SFrançois Revol * @param buffer where to store the name to.
25158a9c38SFrançois Revol * @param bufferSize length of the buffer.
26158a9c38SFrançois Revol * @return 0 on success, -1 on error, sets errno.
27f2912266SDaniel Reinhold */
28158a9c38SFrançois Revolint
29158a9c38SFrançois Revolttyname_r(int fd, char *buffer, size_t bufferSize)
30f2912266SDaniel Reinhold{
31f2912266SDaniel Reinhold	struct stat fdStat;
32ea2aba5dSAxel Dörfler
33f2912266SDaniel Reinhold	// first, some sanity checks:
34f2912266SDaniel Reinhold	if (fstat(fd, &fdStat) < 0)
3580e1f0e4SFrançois Revol		return ENOTTY;
36ea2aba5dSAxel Dörfler
3780e1f0e4SFrançois Revol	if (!S_ISCHR(fdStat.st_mode) || !isatty(fd))
38158a9c38SFrançois Revol		return ENOTTY;
39ea2aba5dSAxel Dörfler
40158a9c38SFrançois Revol	// just ask devfs
4180e1f0e4SFrançois Revol	if (ioctl(fd, B_GET_PATH_FOR_DEVICE, buffer, bufferSize) < 0)
4280e1f0e4SFrançois Revol		return errno;
4380e1f0e4SFrançois Revol	return 0;
44158a9c38SFrançois Revol}
45ea2aba5dSAxel Dörfler
46ea2aba5dSAxel Dörfler
47158a9c38SFrançois Revol/**
48158a9c38SFrançois Revol * give the name of a tty fd.
49158a9c38SFrançois Revol * @param fd the tty to get the name from.
50158a9c38SFrançois Revol * @return the name of the tty or NULL on error.
51158a9c38SFrançois Revol */
52158a9c38SFrançois Revolchar *
53158a9c38SFrançois Revolttyname(int fd)
54158a9c38SFrançois Revol{
55158a9c38SFrançois Revol	static char pathname[MAXPATHLEN];
56ea2aba5dSAxel Dörfler
57158a9c38SFrançois Revol	int err = ttyname_r(fd, pathname, sizeof(pathname));
5880e1f0e4SFrançois Revol	if (err != 0) {
59ae901935SOliver Tappe		__set_errno(err);
60158a9c38SFrançois Revol		return NULL;
6180e1f0e4SFrançois Revol	}
62158a9c38SFrançois Revol	return pathname;
63f2912266SDaniel Reinhold}
64