本文介绍了创建“目录"使用 CreateProcess 函数的命令失败,错误代码为 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在玩 Win32-API,想使用 CreateProcess 函数创建一个进程.我使用了 MSDN 网站上的以下代码:

I was just playing with Win32-API and wanted to create a process using CreateProcess function. I used the following code from MSDN website:

#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 64Bit.但是当我在 Windows 10 中运行相同的可执行文件时,一切正常.

But surprisingly I can't create a dir process using this piece of code. Error code indicated that 'The system cannot find the file specified.'
I'm using Visual studio 2015 and Windows 7 64Bit. But when I run the same executable in Windows 10, everything is OK.

推荐答案

dir 不是可以运行的外部命令.它是 Windows 命令提示符的内部命令.您需要将您的程序称为 myprogram "cmd/c dir" 来执行此操作.

dir is not an external command that can be run. It's a command internal to the Windows Command Prompt. You'll need to call your program as myprogram "cmd /c dir" to do that.

当然,有比调用外部程序更好的方法来迭代目录,但这是一个单独的问题.

Of course, there are better ways to iterate a directory than calling an external program, but that's a separate question.

这篇关于创建“目录"使用 CreateProcess 函数的命令失败,错误代码为 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:29