2
如何在2進程之間傳遞整數值?如何在2進程之間傳遞整數值c
例如:
我有2個進程:child1和child2。 Child1向child2發送一個整數。 Child2然後將該值乘以2並將其發回給child1。子1然後顯示該值。
如何在Windows平臺上的C中執行此操作?有人可以提供一個代碼示例顯示如何做到這一點?
如何在2進程之間傳遞整數值?如何在2進程之間傳遞整數值c
例如:
我有2個進程:child1和child2。 Child1向child2發送一個整數。 Child2然後將該值乘以2並將其發回給child1。子1然後顯示該值。
如何在Windows平臺上的C中執行此操作?有人可以提供一個代碼示例顯示如何做到這一點?
IPC(或Inter-process communication)確實是一個廣泛的主題。
您可以使用共享文件,共享內存或信號等等。
哪一個使用真正取決於您,並取決於您的應用程序的設計。
因爲你寫你自己使用的是Windows,這是一個使用管道的工作示例:
請注意,我治療緩衝區空值終止字符串。你可以把它當作數字。
服務器:
// 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
#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;
}
希望幫助!
你可以用管道來做到這一點。此鏈接可能會有所幫助 - http://stackoverflow.com/questions/12864265/using-pipe-to-pass-integer-values-between-parent-and-child – Razib 2015-04-05 16:08:08
如何使用書面文本將信息傳遞給讀者:開始該句子使用大寫字母。用句號「。」結束一個句子。 – alk 2015-04-05 16:11:20
@alk對不起。下次我會更加小心 – thanh 2015-04-05 16:27:59