在程序中运行程序,两次

C++ Run program within program, twice

本文关键字:程序 两次 运行      更新时间:2023-10-16

我正在努力开发一个系统,使我能够编译一个可以运行我制作的其他程序的。exe。现在,它可以,但它只能运行一次外部程序。一切运行在一个cmd窗口。我输入一个命令,它执行操作(运行一个单独的.exe),然后等待第二个操作。

我会尽量简化我正在做的事情。

正在运行的。exe。我们把它命名为TheCauser.exe

int main()
{
.
.
.
if(stuff is met)
                {
                    .
                    .
                    .
                    system(foundtextchar);//Windows run program
                    cout << endl;
                }
}

要从上面的代码运行的。exe。命名为DoMe.exe

int main()
{
    //It just does whatever
    .
    .
    .
    return 0;
} 

绝对基本的。虽然事情运行顺利,我只能运行DoMe.exe,并有材料出现在cmd窗口一次。种。我在causer .exe中有一个小通知,告诉我何时DoMe.exe正在运行。当我第二次运行DoMe.exe时,通知出现了,但没有来自DoMe.exe的材料。我的假设是,一旦DoMe.exe第一次运行,它就不会真正关闭,而是继续运行。

我觉得有必要提一下,如果我想运行第二个程序,我们叫它heylisten。exe,如果dome。exe之前在运行,heylisten。exe不会显示它的材料但是会弹出通知说它正在运行。HeyListen.exe将以与DoMe.exe相同的方式构建。

我觉得如果我的问题是在DoMe.exe,在那,它没有结束它的进程的方式,我希望它做的。这是正确的吗?我怎么才能让它工作呢?

我想张贴一张cmd窗口的图片,以帮助给一个视觉,但显然我没有足够的声誉。对不起。

使用CreateProcess()生成程序。(https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx)

示例(来自MSDN)

#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain( int argc, TCHAR *argv[] )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );
    if( argc != 2 )
    {
        printf("Usage: %s [cmdline]n", argv[0]);
        return;
    }
    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        argv[1],        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    ) 
    {
        printf( "CreateProcess failed (%d).n", GetLastError() );
        return;
    }
    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );
    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}