简体   繁体   中英

How can I start/end a C++ Console Application from another C++ Console Application?

So I made two console applications separately one named "The Periodic Table" and the other named "Search Element" .

The "Search Element" application is the sub part of "The Periodic Table" application. So it means that I want to call "Search Element" from "The Periodic Table" and I want to end all the instances of "Search Element" when the user closes "The Periodic Table" .

So how can I do that??

Additional Information

Operating System: Windows 7 32-bit Compiler: Visual C++

  • Use system() call.

    In your The Periodic Table program, call Search Element as follows:

     system("Search Element.exe"); 

    Check out here for another example.

  • Alternatively, you can use CreateProcess() . Check out example here .

Here is the sample. Note that there is no error or Ctrl+C handling.

int main()
{
    std::vector < PROCESS_INFORMATION > processes_;

    while (true)
    {
        char command_;

        std::cout << "Press n for new Notepad instance or x for Exit\n";
        std::cin >> command_;

        switch(command_)
        {
            case 'n':
            case 'N':
            {
                std::array<TCHAR, 1024> args_ = {};

                PROCESS_INFORMATION info_;

                STARTUPINFO details_ = {};

                details_.cb = sizeof(details_);

                if(CreateProcess(_T("C:\\Windows\\System32\\Notepad.exe"), args_.data(), NULL, NULL, false, 0, NULL, NULL, &details_, &info_))
                    processes_.push_back(info_);

                break;
            }

            case 'x':
            case 'X':
            {
                for(auto process_ : processes_)
                {
                    TerminateProcess(process_.hProcess, 0);

                    CloseHandle(process_.hProcess);
                    CloseHandle(process_.hThread);
                }

                processes_.resize(0);
            }

            default:
            {
                std::cin.clear();
                std::cout << "Invalid input";
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM