Threaded C programs in minGW

前端 未结 3 1092
忘了有多久
忘了有多久 2020-12-06 16:03

I am creating a program that intercepts all packets when a certain link is down. I would need to implement the sniffer and the link-checker as threads. But

相关标签:
3条回答
  • 2020-12-06 16:20

    With MinGW you have some options. My recomendations:

    1. Use native Windows API to make your threads.

    2. Use a good library to manage that. I usually use a C++ framework called JUCE to have a better life.

    Using Windows API you could try something like this:

    /*
     *  main.c
     *
     *  Created on: 18/10/2011
     *  Author: Cesar Carlos Ortiz Pantoja.
     */
    
    #include <windows.h>
    #include <stdio.h>
    
    int exitCondition;
    
    struct threadParams{
        int param1;
        int param2;
    };
    
    static DWORD WINAPI myFirstThread(void* threadParams)
    {
        struct threadParams* params = (struct threadParams*)threadParams;
    
        while(exitCondition){
            printf("My Thread! Param1:%d, Param2:%d\n", params->param1, params->param2);
            fflush(stdout);
            Sleep(1000);
        }
    
        return 0;
    }
    
    int main(void){
        DWORD threadDescriptor;
        struct threadParams params1 = {1, 2};
        exitCondition = 1;
    
        CreateThread(
            NULL,                   /* default security attributes.   */
            0,                      /* use default stack size.        */
            myFirstThread,          /* thread function name.          */
            (void*)&params1,        /* argument to thread function.   */
            0,                      /* use default creation flags.    */
            &threadDescriptor);     /* returns the thread identifier. */
    
        while(1){
            printf("Main Program!\n");
            fflush(stdout);
            Sleep(2000);
        }
    
        return 0;
    }
    

    Regards

    0 讨论(0)
  • 2020-12-06 16:31

    You have to use WIN 32 Threads API see http://www.mingw.org/wiki/Use_the_thread_library http://msdn.microsoft.com/en-us/library/ms684254(v=vs.85).aspx

    0 讨论(0)
  • 2020-12-06 16:35

    MinGW doesn't provide a full POSIX model. If you want threads in the standard package, you'll have to use the Windows variety.

    It states on the MinGW main page:

    MinGW compilers provide access to the functionality of the Microsoft C runtime and some language-specific runtimes. MinGW, being Minimalist, does not, and never will, attempt to provide a POSIX runtime environment for POSIX application deployment on MS-Windows. If you want POSIX application deployment on this platform, please consider Cygwin instead.

    Cygwin does have pthreads support because it provides the Cygwin DLL, an emulation layer, whereas MinGW is more gcc for use with the Windows way of doing things.

    Alternatively, if Cygwin isn't an option, you can look into Pthreads/Win32 which claims to work with MinGW.

    0 讨论(0)
提交回复
热议问题