c++ - c ++在线程中执行系统函数
问题描述
当我在线程中执行系统时,什么也没有发生。有解决办法吗?
#include <iostream>
#include <Windows.h>
using namespace std;
void runffplay()
{
const char* _cmd = "ffplay -fs -loop 0 \"D:\\dynamic wallpaper\\1.mp4\"";
system(_cmd);
}
CloseHandle(CreateThread(0, 0, (PTHREAD_START_ROUTINE)runffplay, 0, 0, 0));
解决方案
你的runffplay()
函数有错误的签名,所以你最终会破坏线程的调用堆栈。阅读CreateThread()
和ThreadProc
文档。
此外,您没有进行任何错误处理。
尝试更多类似的东西:
#include <iostream>
#include <cstdlib>
#include <Windows.h>
DWORD WINAPI runffplay(LPVOID)
{
// instead of system(), consider using exec..(), or CreateProcess() directly...
const char* _cmd = "ffplay -fs -loop 0 \"D:\\dynamic wallpaper\\1.mp4\"";
int ret = std::system(_cmd);
std::cout << "system() returned " << ret << std::endl;
return 0;
}
HANDLE hThread = CreateThread(NULL, 0, runffplay, NULL, 0, NULL);
if (!hThread) {
DWORD err = GetLastError();
std::cerr << "CreateThread() failed with error " << err << std::endl;
}
else {
...
CloseHandle(hThread);
}
否则,直接使用std::thread
而不是CreateThread()
:
#include <iostream>
#include <thread>
#include <cstdlib>
void runffplay()
{
// instead of system(), consider using exec..(), or CreateProcess() directly...
const char* _cmd = "ffplay -fs -loop 0 \"D:\\dynamic wallpaper\\1.mp4\"";
int ret = std::system(_cmd);
std::cout << "system() returned " << ret << std::endl;
}
std::thread thrd;
try {
thrd = std::thread(runffplay);
}
catch (const std::system_error &e) {
std::cerr << "thread failed with error " << e << std::endl;
}
...
if (thrd.joinable()) {
thrd.join();
}
推荐阅读
- wordpress - 在 Gatsby 和 GraphQL 中过滤 wordpress 中的 ACF Post Object-field
- java - 没有将 ksoap 连接到 Web 服务
- asp.net-core - ASP.NET Core JWT 身份验证受众属性
- powerbi - Power BI DAX 中的 VALUES 和 DISTINCT 函数有什么区别?
- ruby-on-rails - 从 rspec 调用 Stripe CLI
- vgg-net - VGG16 在更改输入形状时遇到问题
- java - 为什么 jshell 允许 lambda 表达式中的非最终自由变量?
- swiftui - 更新内容时未更新 Equatable 对象
- python - sqlite 数据库没有更新我的烧瓶 webhook python 代码中的表
- javascript -