Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to logoff in Linux

Status
Not open for further replies.

bardley

Programmer
May 8, 2001
121
US
Is it possible to log the user off from a C program in Linux? If so, how? Brad Gunsalus
Cymtec Systems, Inc.
bgunsalus@cymtec.com
 
Basic method is simple:
1) get the pid of the login process for the userid
you want.
2) send the proper signal to the process.

As far as actual code for this...
I wouldn't do it in C, I would roll something in the
shell or awk, it would be simpler.
 
Brad:

Interesting question. Are you asking

1) if root can kill a specific user from a "C" program. Yes, but what do you do if the user is logged in more than once.

2) if the user can self-terminate from a running "C" program. Yes, but the program needs to get the user's parent process and kill that.

Let me know which one you're interested in (or have I completely missed the boat?)

Regards,
 
Thanks for the ideas. Here's some test code I used. It seems to work ok. (Need to run as root)

Code:
#include <stdio.h>

int main (void) {
   FILE *fp;
   int pid;
   char pidstr[10];
   char kill_line[50] = &quot;kill &quot;;

   if ((fp = popen(&quot;ps | grep login&quot;, &quot;r&quot;)) == NULL) {
      printf(&quot;didn't work\n&quot;);
      exit(1);
   }
   fscanf(fp, &quot;%d&quot;, &pid);
   sprintf(pidstr, &quot;%d&quot;, pid);
   strcat(kill_line, pidstr);
   printf(&quot;%s\n&quot;, kill_line);

   if (system(kill_line)) {
      printf(&quot;didn't work\n&quot;);
   }
   return 0;
}
Brad Gunsalus
Cymtec Systems, Inc.
bgunsalus@cymtec.com
 
Last word from me on this:
You are using many system calls anyway, it's a waste of time to do this in C IMO.

logout() {
ps -aux | grep &quot;login&quot; | awk -v name=&quot;username&quot; ' {
if (NR == 1 && $13 == name) {
system(&quot;kill -kill&quot; $2)
}
}'
}

One problem with doing this in C is that the login process is owned by root, so you will have to do some gymnastics to find out who the user is.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top