简体   繁体   中英

Execute command line from C program

I need to execute the following command from ac 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM