现在的位置: 首页 > 综合 > 正文

【Win32API】CreateProcess启动脚本

2019年05月15日 ⁄ 综合 ⁄ 共 1149字 ⁄ 字号 评论关闭

脚本

ping -w 1000 -n %1 1.0.0.1
exit

c代码

#include "stdafx.h"
#include <string>
#include <Windows.h>

static void runScript(const char * cmdline);

int _tmain(int argc, _TCHAR* argv[])
{
    runScript(" /k c:\\temp\\sleep.bat 5");
    return 0;
}

void runScript(const char * cmdline)
{
    STARTUPINFOA startInf;
    memset( &startInf, 0, sizeof startInf );
    startInf.cb = sizeof(startInf);
    // If you want to redirect result of command, set startInf.hStdOutput to a file
    // or pipe handle that you can read it, otherwise we are done!
    PROCESS_INFORMATION procInf;
    memset( &procInf, 0, sizeof procInf );

    char cmd[ MAX_PATH ];
    size_t nSize = _countof(cmd);
    getenv_s( &nSize, cmd, "COMSPEC" );
    BOOL b = CreateProcessA( cmd, (char *)cmdline, NULL, NULL, FALSE,
        NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, NULL, NULL, &startInf, &procInf );

    DWORD dwErr;
    if( b ) {
        // Wait till cmd do its job
        WaitForSingleObject( procInf.hProcess, INFINITE );
        // Check whether our command succeeded?
        GetExitCodeProcess( procInf.hProcess, &dwErr );
        // Avoid memory leak by closing process handle
        CloseHandle( procInf.hProcess );
    }
}

抱歉!评论已关闭.