how to pass integer value between 2 process in c

前端 未结 1 1342
醉酒成梦
醉酒成梦 2021-01-22 09:01

How can I pass an integer value between 2 processes?

For example:
I have 2 processes: child1 and child2. Child1 sends an integer number to child2.

相关标签:
1条回答
  • 2021-01-22 09:31

    IPC (or Inter-process communication) is indeed a broad subject.
    You can use shared files, shared memory or signals to name a few.
    Which one to use is really up to you and determined by the design of your application.

    Since You wrote that You are using windows, here's a working example using pipes:

    Note that I'm treating the buffer as null-terminated string. You can treat it as numbers.

    Server:

    // Server
    #include <stdio.h>
    #include <Windows.h>
    
    #define BUFSIZE     (512)
    #define PIPENAME    "\\\\.\\pipe\\popeye"
    
    int main(int argc, char **argv)
    {
        char msg[] = "You too!";
        char buffer[BUFSIZE];
        DWORD dwNumberOfBytes;
        BOOL bRet = FALSE;
        HANDLE hPipe = INVALID_HANDLE_VALUE;
    
        hPipe = CreateNamedPipeA(PIPENAME,
            PIPE_ACCESS_DUPLEX,
            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
            PIPE_UNLIMITED_INSTANCES,
            BUFSIZE,
            BUFSIZE,
            0,
            NULL);
    
        bRet = ConnectNamedPipe(hPipe, NULL);
    
        bRet = ReadFile(hPipe, buffer, BUFSIZE, &dwNumberOfBytes, NULL);
        printf("receiving: %s\n", buffer);
    
        bRet = WriteFile(hPipe, msg, strlen(msg)+1, &dwNumberOfBytes, NULL);
        printf("sending: %s\n", msg);
    
        CloseHandle(hPipe);
    
        return 0;
    }
    

    Client:

    // client
    #include <stdio.h>
    #include <Windows.h>
    
    #define BUFSIZE     (512)
    #define PIPENAME    "\\\\.\\pipe\\popeye"
    
    int main(int argc, char **argv)
    {
        char msg[] = "You're awesome!";
        char buffer[BUFSIZE];
        DWORD dwNumberOfBytes;
    
        printf("sending: %s\n", msg);
        CallNamedPipeA(PIPENAME, msg, strlen(msg)+1, buffer, BUFSIZE, &dwNumberOfBytes, NMPWAIT_WAIT_FOREVER);
        printf("receiving: %s\n", buffer);
    
        return 0;
    }
    

    Hope that helps!

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