Noonsom
Noonsom

Reputation: 1

How to run another external console program from a console program?

Hello Stack overflow users! I have a problem making the program and I ask a question,,

Here are two console programs. ( I Make to Visual Studio 2017 C++ )

The first Program name is "A", second Program name is "B". Both programs A and B are console programs.

  1. Program "A" checks whether program "B" is running normally.
  2. If program "B" is terminated, program "B" is forcibly executed by program "A".

I had a problem in number 2.. Program "B" must be run as an external program separate from program "A". But now,, program "B" runs in program "A" console prompt..

Please tell me How to run as a separate program.. Thx.

my code is :

int main()   //Program A
{
    STARTUPINFO si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    
    ShowWindow(::GetConsoleWindow(), SW_SHOW);

    while (true)
    {
        if (CheckRef == true)
        {
            //ShowWindow(::GetConsoleWindow(), SW_HIDE);
            std::cout << "  " << getStateProcess(ProcessName) << std::endl;
            
            if (getStateProcess(ProcessName) == 0)  // Check to Program "B" is Running?
            {
                // Program "B" is not Running. Started Program "B"
                CreateProcess(NULL, (LPSTR)ProcessPath, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
                Sleep(10);
            }
        }
        else
        {
            ShowWindow(::GetConsoleWindow(), SW_SHOW);
            system("cls");
            std::cout << "Start Ref Settring. . ." << std::endl;
            SetRef();
        }
        Sleep(500);
    }
    
    return 0;
}`

Upvotes: 0

Views: 494

Answers (2)

Rita Han
Rita Han

Reputation: 9700

I had a problem in number 2.. Program "B" must be run as an external program separate from program "A". But now,, program "B" runs in program "A" console prompt..

CREATE_NEW_CONSOLE seems what you are looking for.

CREATE_NEW_CONSOLE: The new process has a new console, instead of inheriting its parent's console (the default).

An example like this:

CreateProcess(NULL, (LPSTR)ProcessPath, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi);

Upvotes: 2

Andreas B
Andreas B

Reputation: 42

I'am not hundred percent sure how to do it on Windows.

But maybe you could apply this solution to Windows somehow.

On Linux you can run bash commands from inside a programm these programms can also be detached from the terminal they are started from. They then run under the user the programm was started with.

Now you might be able to let your programm B check and if A is not running then you can start your programm A with a call of the system terminal. Maybe powershell.

If someone knows if this method is applicable on Windows they mabe could aggree or disagree with me.

Upvotes: 0

Related Questions