JerusalemSky 发表于 2021-1-6 16:24

VC创建子进程静默执行解压、转移等命令行

本代码经过VS2019测试,调试了很久的命令,欢迎参考。

#include <iostream>

int testPopen()
{
    std::string strCmd;
    int iResult = 0;

      //测试解压PDX,然后将解压出来的jar文件和dll文件移动到jarFILE目录,然后删除解压目录
      std::string strPdxFullPath = ".\\1\\2\\3\\4\\5\\PDX\\202036_TT_0806000200_MD.pdx";
      std::string strFolderName = strPdxFullPath.substr(strPdxFullPath.find_last_of("\\") + 1, strPdxFullPath.size() - strPdxFullPath.find_last_of("\\") - 1 - 4);
      std::string strPdxFolder = strPdxFullPath.substr(0, strPdxFullPath.find_last_of("\\") + 1);

      std::string strPdxDIRFullName = ".\\1\\2\\3\\4\\5\\PDX\\" + strFolderName + "\\";
      std::string strJarDIRFullName = strPdxDIRFullName + "*.jar ";
      std::string strDllDIRFullName = strPdxDIRFullName + "*.dll ";
      std::string strFullExeCmd = "cmd.exe /C .\\1\\2\\3\\4\\7z.exe -y x \".\\1\\2\\3\\4\\5\\PDX\\*.pdx\" -o" + strPdxDIRFullName + " -aoa";//;

      strCmd += strFullExeCmd;
      //strCmd += " > myError.txt";

      //strCmd += "&&if exist \".\\jarFILE\\\" rd /s /q .\\jarFILE\\&&if not exist \".\\jarFILE\\\" mkdir .\\jarFILE\\";

      //strCmd += "&&rd / q / s \".\\jarFILE\\\"&&mkdir .\\jarFILE\\";
      //strCmd += "&&mkdir .\\jarFILE\\ -p";
      strCmd += " > myError.txt";
      
      strCmd += "&&move /y \"" + strDllDIRFullName + "\" \".\\jarFILE\\\"";      
      strCmd += "&&move /y \"" + strJarDIRFullName + "\" \".\\jarFILE\\\"";
      strCmd += " > myError.txt";
      
      strCmd += "&&rmdir / s / q " + strPdxDIRFullName;
      strCmd += " > myError.txt";

    strCmd += " > myError.txt";

    SECURITY_ATTRIBUTES   sa;
    HANDLE   hRead, hWrite;
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;
    if (!CreatePipe(&hRead, &hWrite, &sa, 0))
    {
      return -1;
    }
    STARTUPINFOA   si;
    PROCESS_INFORMATION   pi;
    si.cb = sizeof(STARTUPINFO);
    GetStartupInfoA(&si);
    si.hStdError = hWrite;
    si.hStdOutput = hWrite;
    si.wShowWindow = SW_HIDE;
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    //关键步骤,CreateProcess函数参数意义请查阅MSDN   

    LPSTR lpStr = const_cast<char*>(strCmd.c_str());

    if (!CreateProcessA(NULL, lpStr, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
    {
      return -1;
    }


    CloseHandle(hRead);


    // 关闭子进程的主线程句柄
    CloseHandle(pi.hThread);
    // 等待子进程的退出
    WaitForSingleObject(pi.hProcess, INFINITE);
    // 关闭子进程句柄
    CloseHandle(pi.hProcess);

    return iResult;
}

兰陵笑笑生 发表于 2021-1-6 16:58

谢谢大佬,学习了
页: [1]
查看完整版本: VC创建子进程静默执行解压、转移等命令行