Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The program hangs on the line system("prog .exe"); async doesn't work correctly

I got a problem with my code. When I try to open prog using system with some progs it works well, but with some for example, with Picasa 3 it stops and waits till Picasa closes. I write to command "Picasa 3.exe" cause it has space in the name, but if I rename it and use start Picasa_3.exe it works correctly. I tried to fix it using async but after 3 secs it only writes to the console Command timed out. and waits till Picasa closes, but it does exit(0);, but still waits till Picasa closes and only then closes.

My code

// Call the system command asynchronously
std::future<int> future = std::async(std::launch::async, executeSystemCommand, command);

// Wait for the response with a timeout of 3 seconds
if (future.wait_for(std::chrono::seconds(3)) == std::future_status::ready) {
    // Command executed within 3 seconds
    std::cout << "Command executed successfully." << std::endl;
}
else {
    // Command did not respond within 3 seconds
    std::cout << "Command timed out." << std::endl;
    exit(0);
}

func executeSystemCommand

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int executeSystemCommand(const std::string& command) {
    // Execute the system command
    std::system(command.c_str());
    return 0;
}

>Solution :

system() is a crude way of launching an executable since it has to launch a command shell which then launches your process. The behaviour is very dependent upon the shell.

You could launch it in a separate thread, but a better solution would be to use one of the _spawn variants or CreateProcess() where you have far greater control over how the process runs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading