Creating "dir" command using CreateProcess function failed with error code 2

1.9k Views Asked by At

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 );
}

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.

2

There are 2 best solutions below

3
On BEST ANSWER

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.

0
On

After hours of going through 1500 lines of C code, it finally dawned on me what my problem was and why it worked on one Windows 10 system of mine but not on another. The system that it worked on, I really did have a DIR.EXE. But is was not the COMSPEC DIR that was running. I had DIR.EXEs in Git and MinGW folders.

Read this for how to correctly use CREATEPROCESS.

https://learn.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createprocessa