c++ 使用CreateProcess函数创建“dir”命令失败,错误代码为2

k4ymrczo  于 2023-03-14  发布在  其他
关注(0)|答案(2)|浏览(260)

我只是在玩Win32-API,想用CreateProcess函数创建一个进程,我使用了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 );
}

但令人惊讶的是,我无法使用这段代码创建dir进程。错误代码指示**“系统无法找到指定的文件。”**
我使用的是Visual studio 2015和Windows 7 64位。但当我在Windows 10中运行相同的可执行文件时,一切正常。

yrefmtwq

yrefmtwq1#

dir不是可以运行的外部命令。它是Windows命令提示符的内部命令。要执行此操作,您需要将程序称为myprogram "cmd /c dir"
当然,有比调用外部程序更好的方法来迭代目录,但这是另一个问题。

zvokhttg

zvokhttg2#

经过几个小时阅读1500行C代码后,我终于明白了我的问题所在,以及为什么它在我的一个Windows 10系统上工作,而在另一个系统上却不工作。它工作的系统,我确实有一个DIR.EXE。但它不是正在运行的COMSPEC DIR。我在Git和MinGW文件夹中有DIR.EXE。
阅读本文了解如何正确使用CREATEPROCESS。
https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createprocessa

相关问题