如何在c中的2个进程之间传递整数值

如何在两个进程之间传递整数值?

例如:
我有2个进程:child1和child2。 Child1向child2发送一个整数。 然后Child2将该值乘以2并将其发送回child1。 然后,子1将显示该值。

如何在Windows平台上的C中执行此操作? 有人可以提供一个代码示例来说明如何做到这一点吗?

IPC(或进程间通信 )确实是一个广泛的主题。
您可以使用共享文件,共享内存或信号等。
使用哪一个取决于您,并由您的应用程序设计决定。

既然你写道你正在使用windows,这是一个使用管道的工作示例:

请注意,我将缓冲区视为以null结尾的字符串。 您可以将其视为数字。

服务器:

 // Server #include  #include  #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  #include  #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; } 

希望有所帮助!