英文:
The program hangs on the line system("prog .exe"); async doesn't work correctly
问题
我遇到了代码问题。尝试用系统打开程序时,一些程序能正常运行,但例如 Picasa 3 就会停止并等待 Picasa 关闭。我写了命令 "Picasa 3.exe"
因为它的名字里有空格,但如果我改名并用 start Picasa_3.exe
就能正常运行。我尝试用异步修复它,但 3 秒后只打印到控制台 Command timed out.
并等待 Picasa 关闭,但它执行了 exit(0);
,仍然等待 Picasa 关闭然后才关闭。
我的代码
// 异步调用系统命令
std::future<int> future = std::async(std::launch::async, executeSystemCommand, command);
// 等待响应,超时时间 3 秒
if (future.wait_for(std::chrono::seconds(3)) == std::future_status::ready) {
// 3 秒内执行完成
std::cout << "Command executed successfully." << std::endl;
}
else {
// 3 秒内无响应
std::cout << "Command timed out." << std::endl;
exit(0);
}
func executeSystemCommand
int executeSystemCommand(const std::string& command) {
// 执行系统命令
std::system(command.c_str());
return 0;
}
英文:
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
int executeSystemCommand(const std::string& command) {
// Execute the system command
std::system(command.c_str());
return 0;
}
答案1
得分: 3
system()
是启动可执行文件的一种粗糙方式,因为它必须启动一个命令 shell,然后启动您的进程。其行为在很大程度上取决于 shell。
您可以在单独的线程中启动它,但更好的解决方案是使用其中之一 _spawn 变体 或 CreateProcess()
,这样您可以更好地控制进程的运行方式。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论