[oclug] how to get a process's tty
Roger Messier
en916 at ncf.ca
Thu Apr 8 15:46:03 EDT 2004
On Thu, 08 Apr 2004 09:50:46 -0400 Joe Burpee <jeb at burkby.com> wrote:
> On Wed, Apr 07, 2004 at 22:51:28 -0400, Roger Messier wrote:
> > Hey all,
> > I need to get a process's tty for a school project. I found that
> > the/proc/<pid>/stat files give the tty number for a process (defined
> > as tty_nr in the man page) as one of the fields, like 34817, but I
> > need the tty name, like pts/1. I've discovered the ttyname()
> > function, but it always returns the string "(null)". Can anyone
> > point me in the right direction? A man page perhaps?
>
> $ tty
> /dev/pts/1
>
> $ cat test-ttyname.c
> #include <unistd.h>
> int main(void) {
> char *P;
> P = ttyname(0);
> printf("%s\n", P);
> }
>
> $ gcc test-ttyname.c && ./a.out
> /dev/pts/1
>
> Joe
Thanks Joe, but I tried that when I first found the ttyname() function,
and as I stated it doesn't do what I need it to. It returns the
terminal connected to a certain file descriptor, which I don't have.
What I need to do is go through the /proc directory, and for each
process, find out what terminal it is attached to.
I've found a solution, but it doesn't feel very elegant to me. The
/proc/<pid>/stat files give the tty number for each process (e.g.
34817). I then go through the /dev/pts directory and stat() each file
there. I then compare one of the struct stat members (st_rdev) returned
by stat() to the tty number found in /proc/<pid>/stat. If they match,
then the file stated (e.g. /dev/pts/1) is the terminal that that process
is attached to.
I was wondering if there was a simpler way of doing what I've just
described. I've been trying to understand the source code for top,
since it gets the tty for each process, but haven't been able to wrap my
head around it.
So if anyone has other suggestions, I'm all ears.
Thanks.
--
Roger Messier
Email: en916 at ncf.ca
Jabber ID: rogerm at nureality.ca
PGP KeyID (pgp.mit.edu): 1827131D
Blessed are they who can laugh at themselves,
for they shall never cease to be amused.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://tux.oclug.on.ca/pipermail/oclug/attachments/20040408/27d72137/attachment.bin
More information about the OCLUG
mailing list