Let's say that I have a bunch of foreground processes like in the following...
[cdalten@localhost ~]$ w
16:14:06 up 49 days, 23:37, 8 users, load average: 1.28, 1.64, 1.04
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
cdalten pts/1 :0.0 16:14 0.00s 0.44s 0.06s w
cdalten pts/2 :0.0 23Sep09 26days 0.40s 0.40s bash
cdalten pts/3 :0.0 Sun18 43:48m 0.46s 0.46s bash
cdalten pts/4 :0.0 27Sep09 20days 0.40s 0.40s bash
cdalten pts/5 :0.0 Sun20 18:47m 5.61s 5.19s irssi
cdalten pts/6 :0.0 Mon17 7:58 1.29s 1.29s bash
cdalten pts/7 :0.0 Mon17 18:27m 0.42s 0.42s bash
cdalten pts/9 :0.0 24Sep09 25days 1.25s 0.83s python
[cdalten@localhost ~]$
Now what I want to do is kill EVERY foreground process except my most recent one. I thought about maybe doing a sort and then kill every process except the most recent one. However, for some strange reason, I think there might be a better and/or saner way to do this. Here is what I've attempted so far..
Code:
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <utmp.h>
#include <string.h>
#include <pwd.h>
#include <unistd.h>
#include <errno.h>
#ifdef LINUX
#include <sys/stat.h>
#endif
#include <fcntl.h>
#define MAX_TTY 20
struct utmp uinfo[MAX_TTY];
int who_am_i(void);
int who_am_i(void)
{
int fd, in = 0;
struct passwd *pwd;
struct utmp user;
char login[UT_NAMESIZE+1];
if ((pwd = getpwuid(geteuid())) == NULL)
(void)strcpy(login, "unknown");
else
(void)strcpy(login, pwd->pw_name);
if ((fd = open(_PATH_UTMP, O_RDONLY)) < 0) {
perror(_PATH_UTMP);
return -1;
}
(void)memset(&uinfo, 0, sizeof (uinfo));
while(read(fd, &user, sizeof(user)) == sizeof(user))
if (strncmp(user.ut_name, login, UT_NAMESIZE) == 0) {
if (in == MAX_TTY) {
return in;
} else {
uinfo[in++] = user;
}
}
close(fd);
return 0;
}
int main(void)
{
if (who_am_i() == -1) {
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
Ideas?