user1255189
user1255189

Reputation: 23

Execute command line from C program

I need to execute the following command from a c program:

clamscan.exe -r C:\testing -d"C:\Documents and Settings\All Users\.clamwin\db" -lC:\testing\results.txt

I am trying to use the CreateProcess function as follows:

res = CreateProcess(NULL, "cmd.exe /c C:\\Program Files\\ClamWin\\bin\\clamscan.exe -r C:\\testing -d \"C:\Documents and Settings\All Users\.clamwin\db\" -lC:\\testing\\results.txt" , NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);

with the following error handling:

if(res!=0) {
// Wait till cmd do its job
    WaitForSingleObject( pi.hProcess, INFINITE );
    // Check whether our command succeeded?
    GetExitCodeProcess( pi.hProcess, &dwErr );
    // Avoid memory leak by closing process handle
    CloseHandle( pi.hProcess );
} else {
    printf("not done");
    dwErr = GetLastError();
}

When I run the program, I receive the following error twice in a messagebox:

cmd.exe - Application Error
The application failed to initialize properly (0x0000005).  Click on OK to terminate the application.

Can anyone help me understand what's the problem? I have even tried passing "cmd.exe" as lpCommandLine but I still get the same error.

Upvotes: 0

Views: 228

Answers (1)

David Heffernan
David Heffernan

Reputation: 612874

I see the following problems:

  1. You don't escape all the backslash characters.
  2. There's no need for cmd here. Start the executable directly.
  3. The second parameter to CreateProcess expects a modifiable buffer, but you pass a literal. You usually get away with it using ANSI because of an implementation detail. But formally it is wrong. Pass a modifiable buffer.

The other thing that could be an issue is how you declared and initialized si. We cannot see that code.

Of course, perhaps your code is fine, but the other application is gagging.

Upvotes: 2

Related Questions