How to force user logoff on Ubuntu using C++? - c++

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.

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");

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.

Related

Sleep() function windows 8 c++

I'm attempting to get the Sleep() function working on a Windows 8 operating system, with c++. So far I haven't found any examples specific to this.
Following from http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298%28v=vs.85%29.aspx i've included the header <Synchapi.h>, though i get "Identifier "Sleep" is undefined". I am able to find the functions SleepConditionVariableCS() and SleepConditionVariableSRW() from Synchapi.h, but not Sleep().
Has anyone managed to use Sleep() on a Windows 8 operating system or know why I am unable to find the function?
You shouldn't be including Synchapi.h directly. Include Windows.h instead.
#include <Windows.h>
int main()
{
Sleep(1000);
return 0;
}
Are you using C++11? If you are you can use:
#include <thread>
template< class Rep, class Period >
void sleep_for( const std::chrono::duration<Rep,Period>& sleep_duration );
Update
The Sleep() function is only available for Desktop Apps. Are you building a formerly known as Metro app? Or an App Store app?
See this article for some work arounds:
http://blogs.msdn.com/b/win8devsupport/archive/2012/11/28/introduce-multi-thread-programming-in-windows-store-apps-part-ii.aspx

Assigning value to float data type crashes program

I'm losing my mind here. Please someone help me understand what is going on.
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <windows.h>
int main(int argc, char *argv[])
{
float test;
printf("You see me\n");
test = 3;
printf("Wont get here\n");
return(0);
}
You see me is printed out then the app crashes before the Wont get here is printed.
Important to note that this compiles and runs fine on my system, but when this exe is transferred to a 32 bit, Windows XP machine it crashes.
Ints, Bools, char data formats work fine, but when I try to use floats/doubles the app just crashes with no error.
Am I not compiling this correctly in Visual Studio Express 2013 in some way that anyone can think of? Should I check myself into the local loony ward?
Okay found the issue with the help of a colleague.
The windows machine has an older processor, Geode Integrated Processor.
Found the answer here: http://msdn.microsoft.com/en-us/library/7t5yh4fd.aspx
Open the Property Pages dialog box for the project.
Select the C/C++ folder.
Select the Code Generation property page.
Modify the Enable Enhanced Instruction Set property.
In my case I needed to change this to /arch:IA32. Bam! Works! Thank you all for the brainstorming session.

How to initialize and load MCR

I incorporated C++ shared library generated from MATLAB in a Win32 console application. The MATLAB program takes 2-3 sec to execute in MATLAB but the console application takes 11-12 seconds to execute. I read this is because of the start up time of MCR and I believe after the MCR is initialized it must take same time as it takes in matlab. So how can I load or initialize the MCR so that it is always in the RAM or cache so that it will take 2-3 sec for the console application to run? Should I have to make an infinity loop so that the MCR is loaded continously?? I am working on Windows OS and I am calling the console application from PHP. Any tutorials or link for that?
I have added the MCR_CACHE_ROOT as an environment variable which points to a folder(not temporary). My console application code is as follows:
// shoes_shared.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "shoes_sharedlibrary.h"
#include <iostream>
#include <string.h>
#include "mex.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
/* Call the MCR and library initialization functions */
//const char *pStrings[]={"-nojvm","-nojit"};
// if (!mclInitializeApplication(pStrings,2))
// {
// fprintf(stderr, "Could not initialize MCR for the application.\n");
// return -1;
// }
if (!shoes_sharedlibraryInitialize())
{
exit(1);
}
mwArray img(argv[1]);
double wt1 = _tstof(argv[2]);
mwArray C(wt1);
double wt2 = _tstof(argv[3]);
mwArray F(wt2);
double wt3 = _tstof(argv[4]);
mwArray T(wt3);
double wt4 = _tstof(argv[5]);
mwArray S(wt4);
test_shoes(img,C,F,T,S);
//shoes_sharedlibraryTerminate();
//mclTerminateApplication();
return 0;
}
I have commented the lines above thinking that it will make it faster but no luck. Any help?
Are you running in debug or release? If you are running in debug, try running in release and see if that solves your problem. Are you using Visual Studio? If so, try opening the modules window there you will see a list of loaded dlls. Check and see if your library is being constantly loaded and unloaded, or if it is loaded once and stays loaded.
I don't know on which vm matlab is running, but for example the JVM there is Nailgun, a Java server that runs in the backgroud and can be called whenever some java applications need to be executed. I know that Matlab uses Java, but I am not shure wheather your DLL still invokes it. So if it does, that might be the problem.
Try to put MCR and all shared library dependencies to RAM drive.
There are lot of ways to create RAM drive. I would suggest to use ImDisk

creating an RInside instance inside a thread

I am interested in writing a c++ program that is capable of running R scripts. For several design reasons I would like to create an instance of RInside, execute a script, grab the result, and destroy the instance; all within a thread. I know that R is not multi-threaded, and that one cannot create multiple instances of RInside. But can I create single instances within isolated threads? When I attempt to do this my code compiles, but I get the following error at run-time:
Error: C stack usage is too close to the limit
Error: C stack usage is too close to the limit
terminate called after throwing an instance of 'Rcpp::binding_not_found'
what(): binding not found: '.AutoloadEnv'
Aborted
Here is the code that produced the error:
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <RInside.h>
void *thread_main(void *args){
RInside R(0,NULL);
/* hope to execute an R script here */
printf("--printing from thread--\n");
return NULL;
}
int main(int argc, char *argv[]){
pthread_t tid;
if( pthread_create(&tid, NULL, thread_main, NULL) ){
printf("failed to create thread\n");
return -1;
}
sleep(1);
return 0;
}
I have tried setting R_CStackLimit = (uintptr_t)-1 as recommended in Writing R Extension, but to no avail.
I am running ubuntu, R version 2.15.2, RInside version 0.2.10.
Is it possible to accomplish this? or do I have to learn something like Rserve?
Thank you so much!
R is, and will likely remain, single-threaded. RInside goes to some length to ensure it is created as a singleton; if you subvert that you get the errors you see above. Within the same executable, you only get one RInside instance so one-per-thread will not work. As you experienced.
See the examples I include in the source on how to cope with the single-threaded backend when using multi-threaded frontends such as Qt or the Wt library for webapps.
Longer term we may be able to do what Rserve does and fork. Code contributions would be welcome, I probably won't have time to work on this.

Is there a C++ function to turn off the computer?

Is there a C++ function to turn off the computer? And since I doubt there is one (in the standard library, at least), what's the windows function that I can call from C++?
Basically, what is the code to turn off a windows xp computer in c++?
On windows you can use the ExitWindows function described here:
http://msdn.microsoft.com/en-us/library/aa376868(VS.85).aspx
and here's a link to example code that does this:
http://msdn.microsoft.com/en-us/library/aa376871(VS.85).aspx
Use the following, assuming you have the privileges):
ExitWindowsEx (EWX_POWEROFF | EWX_FORCEIFHUNG,
SHTDN_REASON_MINOR_OTHER);
This will cause power off while giving applications a chance to shut down (if they take too long, they'll be terminated anyway).
It's part of the Win32 API rather than standard C++ but that's because C++ provides no way to do this directly.
You can shutdown by utilizing the system() function.
for Windows
system("shutdown -s");
for Linux
system("poweroff");
or
system("init 0");
You can do this in Windows, by calling the ExitWindowsEx function.
yes!
for Windows XP:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Do you want to shutdown your computer now (y/n)\n");
scanf("%c", &ch);
if (ch == 'y' || ch == 'Y')
system("C:\\WINDOWS\\System32\\shutdown -s");
return 0;
}
For Windows 7
system("C:\\WINDOWS\\System32\\shutdown /s");
For Linux
system("shutdown -P now");
[ FOR WINDOWS ]
None of other solutions worked for me, I wanted to shutdown my customized windows and without explorer this codes simply don't work.
The important note is timeout time, so here's the real solution for windows :
GenericFunction(void, Shutdown)()
{
WinExec("shutdown -s -t 0", SW_HIDE);
Sleep(500); // Works without this but it's safer to use sleep
KillProcessTree("winlogon"); // Internal process killer you can use pskill64
// WinExec("pskill64 winlogon -t -nobanner /accepteula", SW_HIDE);
exit(-10); // Planned Shutdown Code
}