首页 文章

C中的线程Syn

提问于
浏览
0

我正在尝试执行一个程序并等待输出,但这在一个线程下运行,但在尝试使用CreateProcess()的'WaitForSingleObject'等待输出时崩溃了程序 .

我也希望在完成'CreateProcess'创建的进程时关闭创建的线程句柄

class test{
    public:
        static void fun2(void * args){
        /*...*/
            if (!CreateProcess( NULL, Args, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &StartupInfo, &ProcessInfo)) {
                return GetLastError();      
            }

            WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
            ULONG rc;
            if(!GetExitCodeProcess(ProcessInfo.hProcess, &rc)){
                status = 0;
            }
        /*...*/
        }
        void fun1(){
        /* ... */
            HANDLE h = NULL; 
            h = CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE)fun2,&data,0,0);
            if(h!=NULL){
                printf("OK\n");
            }
        /* ... */
        }
};

int main(){
    test t;
    t.fun1();
    return 0;
}

1 回答

  • 2

    主要问题(在您提供的片段中)与此部分有关: (LPTHREAD_START_ROUTINE)fun2 .

    您的 fun2 与ThreadProc不兼容 . ThreadProc声明为:

    DWORD WINAPI ThreadProc(LPVOID lpParameter);
    

    WINAPI 解析为 __stdcall 这是默认 cdecl 的另一个调用约定 . 作为快速修复,您可以将 WINAPI 添加到 fun2 声明中 . 这可能有所帮助 . 如果没有,请提供更完整的示例(阅读如何创建mcve),人们可以编译并重现错误 .

    或者只使用 std::thread ,这将更加便携 .

    例:

    #include <stdio.h>
    #include <thread>
    
    class test{
        public:
            static void fun2(void * args){
                printf("OK from thread\n");
            }
            void fun1(){
                std::thread t([]{
                    fun2(nullptr);
                });
                printf("OK\n");
                t.join();
            }
    };
    
    int main(){
        test t;
        t.fun1();
        return 0;
    }
    

    注意 std::thread 的生命周期 - 如果在线程仍在运行时它被销毁,整个程序将终止 . 在 std::thread 之前调用 join 超出范围,从而确保正确的操作顺序 .

相关问题