IPC (or 进程间通信)确实是一个广泛的主题。
您可以使用共享文件、共享内存或信号等。
使用哪一种实际上取决于您并由应用程序的设计决定。
由于您写道您正在使用 Windows,因此这里有一个使用管道的工作示例:
请注意,我将缓冲区视为以空字符结尾的字符串。您可以将其视为数字。
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;
}
希望有帮助!