1

Need help here, I'm trying to create a process in c++ with the windows api, whats happening is the process is being created which is cmd.exe however I want cmd.exe to open cd'd at a certain directory i.e. root c:\, however the process is opened at the dir of the executable. I tried passing in "cd \" as the second argument of the CreateProcess function to no avail

Here's a snippet of the code:

TCHAR program[] = TEXT("C:/Windows/System32/cmd.exe");
TCHAR command[] = TEXT("cd /");
STARTUPINFO info;
PROCESS_INFORMATION processInfo;
ZeroMemory(&info,sizeof(STARTUPINFO));
ZeroMemory(&processInfo,sizeof(PROCESS_INFORMATION));

BOOL processResult =
CreateProcess(program,
            command, NULL, NULL,
            TRUE, CREATE_NEW_CONSOLE,
            NULL, NULL,
            &info,
            &processInfo);

if(!processResult){
 std::cerr << "CreateProcess() failed to start program \""
 << program << "\"\n";
 exit(1);
}

std::cout << "Started program \""
<< program << "\" successfully\n";    

Help would be extremely appreciated! Thanks

Barmar
  • 741,623
  • 53
  • 500
  • 612
Ian Bastos
  • 83
  • 2
  • 5
  • [edit] Cd to the directory, then run the process. Check out.[/edit] http://stackoverflow.com/questions/3485166/change-the-current-working-directory-in-c – Aumnayan May 05 '17 at 17:04
  • You could use `ShellExecute` instead. –  May 05 '17 at 17:11

1 Answers1

2

If you want the cd / (or any other command) to have any effect, you need to use either the /k or /c flags for the command prompt. You can look these switches up in the documentation for cmd.exe, but basically, /c runs the command and then terminates, while /k runs the command and keeps the console session open. You almost certainly want /k here.

But really, you should be specifying the directory as the working directory for the process, not executing a change-directory command.

You can do this easily by calling the ShellExecute function, as Raw N suggested. The working directory is one of its parameters. ShellExecute (or ShellExecuteEx) is easier to use than CreateProcess, and should be preferred unless you need some special low-level behavior that you can only get with CreateProcess.

This works with CreateProcess too: pass the path as the lpCurrentDirectory parameter.

Whatever you do, don't hard-code paths! Use the %comspec% environment variable on Windows NT. It would also work to just execute cmd, letting the default search paths do their job.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • `ShellExecuteEx()` should always be used instead of `ShellExecute()` because the latter has poor error reporting (only a limited set of non-standard return values). It should also be noted that `CreateProcess()` has less overhead than `ShellExecute()`. – zett42 May 05 '17 at 18:44
  • Perfectly detailed answer and answers everything that I wanted and more, thank you – Ian Bastos May 05 '17 at 23:35