1

i have been working on a small project. i am making a timer for my little brother's PC so that he will not be able to use computer more than set time by me in a day. The problem I am facing in my code is I have tried bunch of system commands to shut down computer automatically but when it runs the command it asks to wether close the running applications. but I want to force shut down all running apps. below is the code i am trying but it is not quite working out

system("C:\\Windows\\System32\\shutdown /s /t 0");

now this statement, when it is executed, asks for closing applications which are running or cancel shut down process

ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
    SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
    SHTDN_REASON_MINOR_UPGRADE |
    SHTDN_REASON_FLAG_PLANNED);

i got this above function from Microsoft docs but it doesn't work in my computer even it doesn't show any error in this statement. but even after executing it doesn't work. moreover visual studio offered its own suggestion of using a new API which is given below

InitiateSystemShutdownEx(NULL, NULL, 0, true, false, SHTDN_REASON_FLAG_USER_DEFINED);

this also doesn't work even if gets execute. i am using windows 11. and below i am giving the whole code where i reached yet

#include <iostream>
#include <stdlib.h>
#include<Windows.h>
#include<fstream>
#pragma warning(disable : 4996)
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "advapi32.lib")
using namespace std;


void timer()
{
    int hours=0;
    int minutes=0;
    int seconds=0;
    ofstream tim;
    while (seconds != 5)
    {
        tim.open("time.txt", ios::out | ios::trunc);
        seconds++;
        Sleep(1000);
        if (seconds == 60)
        {
            minutes++;
            seconds = 0;
        }
        if (minutes == 60)
        {
            hours++;
            minutes = 0;
        }
        tim << hours << endl << minutes << endl << seconds;
        tim.close();
    }
}

int main()
{
    timer();
    ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
        SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
        SHTDN_REASON_MINOR_UPGRADE |
        SHTDN_REASON_FLAG_PLANNED);
    cout << endl << endl;
    return 0;
}

so please just any type of help would be appreciated.

5
  • 1
    (1) Since you're using C++, you'd be better off using the tools in std::chrono to implement your time-conversion logic as well as your sleep operation. Simpler code. (2) ExitWindowsEx and/or InitiateSystemShutdownEx are the APIs you should be calling. Avoid using the system function; there's never a good use for this. (3) Note that this operation (shutting down a computer) requires elevated privileges. Are you running this app as an administrator? (Technically, you need the SE_SHUTDOWN privilege.) Call GetLastError to find out why it fails. Commented Aug 12, 2022 at 22:50
  • Here's some helpful reading on programmatic solutions : learn.microsoft.com/en-us/windows/win32/shutdown/… Commented Aug 12, 2022 at 22:51
  • 2
    Hopefully your end result will be a bit friendlier and give a warning so he can save what he's doing. Personally I'm rooting for the little dude to find all the ways to disable this and keep you on your toes. Commented Aug 12, 2022 at 22:56
  • @RetiredNinja haha it was a gud one...but this little dude is always playing games and never studying....he never uses computer or internet to learn something creative or productive even though I tried so much to make his time useful....so its better he give less time to computer and more to family and studies and his real world games and friends rather than just playing fortnite or pubg for 10 hours.... Commented Aug 12, 2022 at 23:00
  • 1
    @mueeburrehman Blindly shutting down his computer is not the best way to handle this. Using a firewall, or even an external device like Circle, to block unwanted content and allow desirable content would be a far better choice. Commented Aug 12, 2022 at 23:09

3 Answers 3

1

You need to add the /f flag to force a shutdown.

Sign up to request clarification or add additional context in comments.

2 Comments

Although this may work and solve the immediate problem, it is worth noting (if nothing else, for future readers) that it is vastly preferable to call the documented API, rather than to shell out to a helper program. Some reasons are listed in this answer. The correct APIs to use in this case are ExitWindowsEx or InitiateSystemShutdownEx. There is never a case where using the system function to invoke shutdown /f would work, but the correct APIs would not work, unless you're mis-calling the APIs.
@CodyGray u r right in ur place but I gotta mark that answer which worked for me obviously...i am in favor of ur answer too because in whole web I saw the examples of API and I also prefer using them...thanks for illustration brother
0

Here's the actual logoff function I created many years ago when faced with a similar problem. There's a lot of extra code there to support debugging without logging myself out, the actual work is in the call to ExitWindowsEx.

void CTimeLimitApp::Logoff()
{
    static bool bOff = false;
    if (bOff)
        return;
    bOff = true;
#if _DEBUG
    AfxMessageBox("Logoff!", MB_OK, 0);
    PostQuitMessage(0);
#else
    Sleep(1000);
    ExitWindowsEx(EWX_LOGOFF | EWX_FORCE, 0);
#endif
}

You may need to run the program as Administrator if you want to do a full shutdown.

6 Comments

_DEBUG is a Visual Studio defined by default for any debug build. It's hard to upvote an answer where the code has a drastically different behavior between release and debug builds. If you really feel a "dry fun" branch is necessary to answer the question, consider using a different preprocessor macro to toggle the behavior independently of the choice of release/debug build configuration.
C++11 introduced std::call_once as an alternative to solutions such as bOff. It provides a solution to that is thread safe and exception safe.
@FrançoisAndrieux you don't need to upvote an answer if you feel it doesn't deserve it. As I said, this is the actual code I used and I thought that copy/paste the whole thing might prove useful to somebody. I really really didn't want to accidentally lose my work while I was fine tuning the program.
@fra Static local variables are thread-safe starting with C++11. The exception safety that std::call_once provides doesn't apply here: The code is strictly calling into C functions, and while those generally provide the basic exception safety guarantee, the way failure is communicated is incompatible with C++' exceptions. This isn't to say that one shouldn't use std::call_once here, but the reason is a different one: Documentation of intent.
@IInspectable Threadsafe static local variable initialization isn't enough to make the approach thread safe. This is a C++11 "gotcha". If this function can be called concurrently, bOff would still have to be synchronized. My 2nd comment is general advice to anyone who would find this code. Regarding documenting intent, I am of the opinion that std::call_once is the clearest way to self-document that the implementer expected a function to only be called once, the argument seems to me like a good reason to switch to std::call_once, and not an argument for keeping the solution shown.
|
0

Adjusting privilege aside of getting admin rights to your process. Notice EWX_FORCEIFHUNG.

bool RebootPC()
{
    HANDLE hToken;
    TOKEN_PRIVILEGES tkp;

    // Get a token for this process.
    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
    {
        std::cerr << "OpenProcessToken failed. Error: " << GetLastError() << '\n';
        return false;
    }

    // Get the LUID for the shutdown privilege.
    LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

    tkp.PrivilegeCount = 1;  // one privilege to set
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    // Get the shutdown privilege for this process.
    AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);

    if (GetLastError() != ERROR_SUCCESS)
    {
        std::cerr << "AdjustTokenPrivileges failed. Error: " << GetLastError() << '\n';
        return false;
    }

    // Shut down the system and force all applications to close
    if (!ExitWindowsEx(EWX_REBOOT | EWX_FORCE | EWX_FORCEIFHUNG, SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED))
    {
        std::cerr << "ExitWindowsEx failed. Error: " << GetLastError() << '\n';
        return false;
    }

    return true;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.