In C ++, how to execute the second 'system()' only after the first one is over?

See the code below. If there is any alternative to system that does what I want it would be good too.

strcat(comando1,"start c:\\arquiv~1\\winrar\\rar a D:\\sisbibbkp\\teste1");
strcat(comando1,data);
strcat(comando1,".rar E:\\softwares");
system(comando1);

strcat(comando2,"start c:\\arquiv~1\\winrar\\rar a D:\\sisbibbkp\\teste2");
strcat(comando2,data);
strcat(comando2,".rar E:\\softwares");
system(comando2);  // I want this system to run only after system (command1) finishes.

Upvotes: 0

Views: 142

Answers (3)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

Just add /WAIT after start.

That makes the process block until the subprocess has completed.

Moving away from start is fine if that's what you want, but it has other consequences. start does more things than alternatives.

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 596397

The correct way to handle this is to not use system() at all. Use CreateProcess() instead to run rar.exe directly, and then you can wait on the spawned process.

std::string comando1 = "c:\\arquiv~1\\winrar\\rar.exe a D:\\sisbibbkp\\teste1" + std::string(data) + ".rar E:\\softwares";

STARTUPINFOA si = {};
si.cb = sizeof(si);
PROCESS_INFORMATION pi;

if (CreateProcessA(NULL, const_cast<char*>(comando1.c_str()), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
    CloseHandle(pi.hThread);
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);
}

std::string comando2 = "c:\\arquiv~1\\winrar\\rar.exe a D:\\sisbibbkp\\teste2" + std::string(data) + ".rar E:\\softwares";

if (CreateProcessA(NULL, const_cast<char*>(comando2.c_str()), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
    CloseHandle(pi.hThread);
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);
}

A better solution is to use a library that handles RAR files directly in your own process, don't shell out to rar.exe at all. You can use WinRAR's UnRar.dll for that, or any number of 3rd party libraries that are available.

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881563

The start command runs things as a separate job:

C:\Users\Pax> start /?
Starts a separate window to run a specified program or command.

If you want to wait for it to finish, just remove the start from the command.

Or if you want the whole thing to run separately but have step 2 wait for step 1 to finish, put both into a cmd script (without the start bits) and start cmd.exe on your script to do it.

That should start a separate job to run the script but that job will run the command in the script sequentially.

Upvotes: 4

Related Questions