首页 > 解决方案 > 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));

标签: c++

解决方案


你的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();
}

推荐阅读