Create Processes with CreateProcess
Start a program from C with CreateProcessW, quote the command line correctly, redirect its output to a file, wait with a timeout and avoid handle leaks.

On Linux, starting a program is two steps: fork makes a copy of the current process and exec replaces the copy with a new program. Windows has no fork. One function, CreateProcess, builds a new process around a program image and starts it, and everything you would arrange between fork and exec, such as redirecting standard output or changing the working directory, you express as arguments to that one call. It takes ten parameters, two of them are structures, and the details of the command line cause more bugs than the rest of the API together. This post builds up from the smallest working call to redirecting a child's output into a file, then waits with a timeout and cleans up, and then shows the quoting rules that decide whether your program launches the right program.
The examples use the Windows 11 SDK (10.0.26100) with MSVC 19.4 on x64. The function is documented on Microsoft Learn as CreateProcessW, and this post uses the wide version, as all new code should.
The smallest call
#include <windows.h>
#include <stdio.h>
int wmain(void)
{
wchar_t cmd[] = L"cmd.exe /c echo hello from the child";
STARTUPINFOW si = { sizeof si };
PROCESS_INFORMATION pi = { 0 };
if (!CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
fwprintf(stderr, L"CreateProcess failed: %lu\n", GetLastError());
return 1;
}
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD code = 0;
GetExitCodeProcess(pi.hProcess, &code);
wprintf(L"exit code: %lu\n", code);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return 0;
}cl /nologo /W4 /DUNICODE /D_UNICODE basic.c
basic.exebasic.c
hello from the child
exit code: 0Reading the call parameter by parameter explains most of the API.
lpApplicationNameisNULL. When it is null, the program to run is the first token of the command line.lpCommandLineis the whole command line, as one string. It must be a writable buffer, which is whycmdis an array and not a pointer to a literal.CreateProcessWis documented to possibly modify it while parsing, and passing a read-only string can crash the program with an access violation.The two
NULLsecurity attributes mean default security for the process and its initial thread, and theFALSEsays the child does not inherit the parent's inheritable handles.0is the creation flags, and the twoNULLs after it are the environment block and the current directory, meaning inherit the parent's.&siis aSTARTUPINFOW, which describes the new process's initial state. Its first field,cb, must be set to its own size, which{ sizeof si }does.&piis where Windows returns the result:hProcess,hThread,dwProcessIdanddwThreadId.
The call returns when the process has been created, not when it has finished. The new process may not even have started executing yet. To wait for it, use WaitForSingleObject on pi.hProcess, which becomes signaled when the process ends. The exit code, which the child passed to ExitProcess or returned from main, is read with GetExitCodeProcess.
The two handles in PROCESS_INFORMATION are yours, and both must be closed. Closing them does not affect the child: it only releases your references. Forgetting is the most common leak in Win32 programs, and each launched program that leaks two handles and a process object that the system keeps around until they are closed.
The command line is one string
On POSIX, execv takes an array of arguments, and the kernel never reparses them. On Windows, the child receives a single string and its runtime splits it into arguments. CreateProcess does not do the splitting for you, and so you must quote it yourself.
The rules follow the convention used by the Microsoft C runtime when it parses argv. An argument with spaces must be enclosed in double quotes. A double quote inside an argument is written as a backslash followed by a quote. Backslashes are literal unless they come right before a quote, and then the count matters.
The most common bug is a path with spaces:
wchar_t bad[] = L"C:\\Program Files\\Tool\\tool.exe --verbose";
wchar_t good[] = L"\"C:\\Program Files\\Tool\\tool.exe\" --verbose";With the bad string and a null application name, CreateProcess tries to interpret the first token in turn: it first tries the text up to the first space as a program name with .exe added, then the text up to the next space, one space at a time, and runs the first one that exists. If an attacker can create a file named Program.exe in the root of the drive, it is launched in place of yours. This is the unquoted service path vulnerability, and it is a real, recurring class of local privilege escalation. The fix is always to quote the program path, or to pass it as the first argument, lpApplicationName, so that Windows takes it exactly as given:
CreateProcessW(L"C:\\Program Files\\Tool\\tool.exe",
L"tool.exe --verbose",
NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);With an application name supplied, no searching happens. The command line still becomes the child's idea of its own arguments, so by convention it starts with the program name, and the first token is what the child sees as argv[0]. Note that when you give an application name with no directory, Windows looks only in the current directory, so give a full path.
Building a command line from user data requires escaping each argument, and doing it correctly is harder than it appears. Microsoft's documentation of the argument parsing rules and the famous write-ups of the escaping problem should be consulted before writing it. A shortcut is to avoid it: pass the arguments in a file, the environment, or a pipe to the child, so that no command line parsing sits between the data and the program.
Redirecting the child's output
A parent that wants a child's output has to give the child different standard handles. The parent opens a file, marks the handle inheritable, and tells CreateProcess to use it for the child's standard output:
#include <windows.h>
#include <stdio.h>
int wmain(void)
{
SECURITY_ATTRIBUTES sa = { sizeof sa, NULL, TRUE }; /* inheritable */
HANDLE log = CreateFileW(L"child.log", GENERIC_WRITE, FILE_SHARE_READ, &sa,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (log == INVALID_HANDLE_VALUE) {
fwprintf(stderr, L"cannot create log: %lu\n", GetLastError());
return 1;
}
STARTUPINFOW si = { sizeof si };
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = log;
si.hStdError = log;
PROCESS_INFORMATION pi = { 0 };
wchar_t cmd[] = L"cmd.exe /c echo to the log && echo this also";
if (!CreateProcessW(NULL, cmd, NULL, NULL, TRUE /* inherit handles */,
CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
fwprintf(stderr, L"CreateProcess failed: %lu\n", GetLastError());
CloseHandle(log);
return 1;
}
CloseHandle(log); /* the child has its own copy */
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
wprintf(L"done; see child.log\n");
return 0;
}cl /nologo /W4 /DUNICODE /D_UNICODE redirect.c
redirect.exe
type child.logdone; see child.log
to the log
this alsoThe trailing space on the first line appears because cmd includes the space before && in the echoed text. The pieces that matter are three. STARTF_USESTDHANDLES in dwFlags tells Windows to read the three standard handle fields, and without it they are ignored. The file handle is created inheritable through sa, and bInheritHandles is TRUE, which are two separate switches that must both be on. And CREATE_NO_WINDOW stops a console window from appearing for a console program.
The parent closes its copy of log right after creating the process: the child already has its own duplicate, and holding the file open in the parent would keep it locked for longer than needed. For capturing the output into the parent's memory, replace the file with an anonymous pipe made by CreatePipe, give the child the write end, close the parent's copy of the write end, and read from the read end until it reports ERROR_BROKEN_PIPE. Forgetting to close the parent's write end is the reason such reads never finish.
Timeouts and killing
An unbounded wait is a bug waiting for a hung child. Wait with a time limit and handle the result:
DWORD r = WaitForSingleObject(pi.hProcess, 5000);
if (r == WAIT_TIMEOUT) {
TerminateProcess(pi.hProcess, 1);
WaitForSingleObject(pi.hProcess, INFINITE);
}TerminateProcess kills the process immediately, without running its cleanup, DLL detach notifications or atexit handlers, so files may be left half written. It is a last resort. A gentler approach for console programs is to send a Ctrl-Break event to the child's process group, which requires creating it with CREATE_NEW_PROCESS_GROUP, and for GUI programs to post WM_CLOSE. After TerminateProcess the process has not necessarily finished by the time the call returns, so waiting once more on the handle is the right way to be sure it is gone.
A job object is the tool for controlling a whole tree of processes. Create one with CreateJobObjectW, add the child with AssignProcessToJobObject, and set JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE so that all processes in the job die when the parent closes its job handle, even if the parent crashes. It is the Windows answer to "do not leave orphans".
Flags worth knowing
| Flag | Effect |
|---|---|
CREATE_NO_WINDOW | A console program runs with no console window |
CREATE_NEW_CONSOLE | Gives the child its own console window |
DETACHED_PROCESS | The child has no console at all |
CREATE_SUSPENDED | The main thread starts suspended, until ResumeThread |
CREATE_NEW_PROCESS_GROUP | The child is the root of a new process group, for Ctrl-Break |
CREATE_UNICODE_ENVIRONMENT | The environment block you pass is UTF-16 |
EXTENDED_STARTUPINFO_PRESENT | si is a STARTUPINFOEXW with an attribute list |
CREATE_SUSPENDED gives you a window to do something to the process before it runs a single instruction of its own, for example assigning it to a job object, so that it can never escape. Resume it with ResumeThread(pi.hThread). The environment block, when you pass one, is a sequence of NAME=value strings, each ended by a zero, with a final extra zero, and with CREATE_UNICODE_ENVIRONMENT set when it is wide, a flag people forget and then see garbage variables in the child.
Errors you will see
The failures are few and have clear causes:
| Code | Meaning in practice |
|---|---|
2 ERROR_FILE_NOT_FOUND | The program was not found on the search path, or the quoted path is wrong |
3 ERROR_PATH_NOT_FOUND | A directory in the path or the working directory does not exist |
5 ERROR_ACCESS_DENIED | No execute permission, or the file is locked or blocked by policy |
87 ERROR_INVALID_PARAMETER | A bad combination of flags or a malformed environment block |
193 ERROR_BAD_EXE_FORMAT | The file is not a valid executable for this system, such as a 32-bit program on an ARM-only machine without emulation, or a corrupt file |
740 ERROR_ELEVATION_REQUIRED | The program's manifest demands administrator rights |
Error 740 is a trap. CreateProcess cannot elevate. A program that requires administrator privileges fails with 740 when started this way, and the correct call is ShellExecuteExW with the verb runas, which shows the consent prompt. CreateProcess is for programs that run at the caller's own level.
When not to use it
CreateProcess is the right tool for starting an executable. It is not the way to open a document or a URL in the default program: ShellExecuteExW does that, honoring file associations. It is not a shell: it does not understand pipes, redirection or wildcards, so a command such as dir > out.txt needs cmd.exe /c in front. And it is not cheap. Creating a process on Windows costs far more than creating a thread, which is why programs that launch many short tasks use threads or a pool of workers rather than a process per task.


