2

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. Child2 would then multiply that value by 2 and send it back to child1. Child 1 would then display the value.

How can I do this in C on the Windows platform? Could someone provide a code sample showing how to do it?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
thanh
  • 55
  • 6
  • You may use pipe to this. This link may be helpful - http://stackoverflow.com/questions/12864265/using-pipe-to-pass-integer-values-between-parent-and-child – Razib Apr 05 '15 at 16:08
  • 2
    How to pass information to a reader using written text: Start the sentence using a capital letter. Terminate a sentence using a full-stop `.`. – alk Apr 05 '15 at 16:11
  • 1
    @alk Sorry. Next time i will be more careful – thanh Apr 05 '15 at 16:27
  • @Razib Thanks you. But I got this error: "(.text+0x3a): undefined reference to `pipe'" when run the code in the link you give me. Do you know how can i fix it ? – thanh Apr 05 '15 at 16:31
  • what you describe is IPC and is way to general and broad. – bolov Apr 05 '15 at 18:04

1 Answers1

1

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!

Yuval
  • 907
  • 9
  • 24