Home > Net >  How to avoid console flickering/opening when executing a system() command in QT?
How to avoid console flickering/opening when executing a system() command in QT?

Time:09-20

I'm working on an implementation to force the exit of a process by PID in QT. The only way I found to solve this problem is using the following lines of code:

QString processToKill = "taskkill /F /PID "   QString(getAppPid());
system(processToKill.toStdString().c_str());    

These lines do their job and works well, the only detail I have found is that when executing this command a console opens and closes quickly (a flicker). Is there any way to prevent this behavior?

CodePudding user response:

If this is a windows program create a program that uses a WinMain entry point rather than main, and set the linker subsystem to windows rather than console.

Just because it uses WinMain does not mean that you must create a window, it merely means you don't automatically get a console.

CodePudding user response:

If you are using system() you cannot avoid the occasional flash of the console window. Were you to use any other program you might even see its window flash.

I won’t go into any detail about the security flaws inherent to using system().

The correct way to do this with the Windows API.

Even so, you are taking a sledgehammer approach. You should first signal the process to terminate gracefully. If it hasn’t done so after a second or two, only then should you crash it.

The SO question “How to gracefully terminate a process” details several options to properly ask a process to terminate.

If that fails, then you can simply kill a process using the TerminateProcess() Windows API function (which is what taskkill /f does). Here is a good example of how to do that: https://github.com/malcomvetter/taskkill

The relevant code has the following function:

BOOL TerminateProcess(int pid)
{
    WORD dwDesiredAccess = PROCESS_TERMINATE;
    BOOL bInheritHandle = FALSE;
    HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, pid);
    if (hProcess == NULL)
        return FALSE;
    BOOL result = TerminateProcess(hProcess, 1);
    CloseHandle(hProcess);
    return(TRUE);
}

Microsoft has a page all about Terminating a Process that you may wish to review as well.

  •  Tags:  
  • c qt
  • Related