用CreateProcess调用另一个exe并传入参数

调用exe代码,传递三个参数分别是20 30 40

#include <iostream>

#include <stdlib.h>
#include <windows.h>

#include <iostream>
#include <tchar.h>
#include <atlstr.h>

using namespace std;
int main() {
    std::cout << "Hello World!\n";
    STARTUPINFO si;
    memset(&si, 0, sizeof(STARTUPINFO));  //初始化si在内存块中的值(详见memset函数)
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags = STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_SHOW;
    PROCESS_INFORMATION pi;  //必备参数设置结束

    TCHAR sCmd[] = _T("D:\\chrono\\workspace\\chrono_build\\bin\\Release\\demo_GPU_ballcosim.exe");

    CString strCmdLine = _T(" 20 30 40"); //传递的参数 前面需要有空格
 
    if (!CreateProcess(sCmd, strCmdLine.GetBuffer(), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
        cout << "CreateFail!" << endl;
        exit(1);
    } else {
        cout << "Success!" << endl;
    }
    //关闭不使用的句柄
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    system("pause");
    return 0;
}

被调用exe代码

#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {
    cout << "argc:"<< argc << endl;
    cout << "argv[1]:"<< std::string(argv[1]) << endl;
    cout << "argv[2]:"<< std::string(argv[2]) << endl;
    cout << "argv[3]:" << std::string(argv[3]) << endl;
    system("pause");
    return 0;
}

argc:argument count,值等于传入参数个数+1

argv:argument vector,argv[0]是程序相关信息

输出:

使用 #include <cstring> 出现报错:

1>D:\.\..cpp(25,5): error C2065: “CString”: 未声明的标识符

使用 #include <atlstr.h> 代替 #include <cstring> 解决

int转cstring后传入参数:

    int num = 80;
    CString s;
    s.Format(_T("%d"), num); 
    CString strCmdLine = _T(" "); //传递的参数 前面需要有空格
    strCmdLine += _T(s);

参考(3条消息) C++ 在一个程序中调用exe_金色暖阳的博客-CSDN博客_c++调用exe

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐