0
votes

I'm trying executing a program and wait the output but this run under a thread but crashed the program when try wait the output with 'WaitForSingleObject' of CreateProcess().

also I want will close handle of thread created when finish the process created by '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
Why not using std::thread and the synchronization mechanisms available from there?user8238559
I'm new with the threads, I will try, thanks.MrNuget

1 Answers

2
votes

The main problem (in the fragment you provided) is with this part: (LPTHREAD_START_ROUTINE)fun2.

Your fun2 is incompatible with ThreadProc. ThreadProc is declared as:

    DWORD WINAPI ThreadProc(LPVOID lpParameter);

WINAPI resolves to __stdcall which is another calling convention from the default cdecl. As a quick fix you can add WINAPI to the fun2 declaration. This may help. If it doesn't, provide a more complete example (read how to create an mcve), something people can compile and reproduce the error.

Or just use std::thread, which will be more portable.

Example:

#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;
}

Beware of the lifecycle of std::thread - if it's destroyed while the thread is still running, the whole program will terminate. A call to join before std::thread goes out of scope thus ensures proper sequence of action.