2

Is there any way to force user log out using C++ in Ubuntu (16.04 or 18.04)? Like if condition is met, I want the program to log out the current user.
In windows 10 we can probably use ExitWindows like this https://learn.microsoft.com/en-us/windows/desktop/shutdown/how-to-log-off-the-current-user.

Is it possible in Ubuntu? I couldn't find a good example how to do it.

jww
  • 97,681
  • 90
  • 411
  • 885
gameon67
  • 3,981
  • 5
  • 35
  • 61
  • I think this is what you need: https://people.gnome.org/%7Emccann/gnome-session/docs/gnome-session.html#org.gnome.SessionManager.Logout – Eelke Mar 12 '19 at 05:45

2 Answers2

2

This is window-manager specific, so it's probably easiest to use an exec function to do it. Ubuntu 18.04 by default uses Gnome, so in Gnome you would do the following:

#include <unistd.h>
#include <stdlib.h>

int main()
{
    if (execl("/usr/bin/gnome-session-quit", "/usr/bin/gnome-session-quit",
            "--no-prompt", (char*) NULL) < 0) 
        printf("Failed to logout\n");
}

I'm not exactly sure where the loginctl program is located for KDE, so I'll assume it's in the same location, so for KDE you would:

    #include <stdlib.h>
    ...
    char *user=getenv("USER");
    if (execl("/usr/bin/loginctl", "/usr/bin/loginctl",
            user, (char*) NULL) < 0) 
        printf("Failed to logout\n");
gameon67
  • 3,981
  • 5
  • 35
  • 61
Major
  • 544
  • 4
  • 19
  • As @UserX mentioned, you can also use `system`. The difference between `exec` functions and `system` can be read about [here](https://stackoverflow.com/questions/1697440/difference-between-system-and-exec-in-linux). Basically, `system` creates a child process, whereas `exec` replaces the currently running process. – Major Mar 12 '19 at 13:27
  • 1
    Thanks for great answer, exactly what I'm looking for. Slightly better than other answer because it will logout immediately without asking for logout permission and doesn't wait for 60 secs. 1 edit, I will add `#include ` – gameon67 Mar 13 '19 at 00:55
1

You can invoke any operating system command using c++ system() from stdlib.h.

#include<stdlib.h>

int main(){
    system("gnome-session-quit"); //logs out.
}

To my knowledge after the above code is executed in ubuntu, it logs out automatically after 60 seconds if there is any unsaved work.

HariUserX
  • 1,341
  • 1
  • 9
  • 17