概述:
之前下载并安装了nanomsg库,接下来就是看看怎么使用啦。首先是看看如何实现进程间的通信吧。
实例demo:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <nanomsg/pair.h>
#include <nanomsg/bus.h>
#include <nanomsg/nn.h>
/*
PAIR - simple one-to-one communication
BUS - simple many-to-many communication
REQREP - allows to build clusters of stateless services to process user requests
PUBSUB - distributes messages to large sets of interested subscribers
PIPELINE - aggregates messages from multiple sources and load balances them among many destinations
SURVEY - allows to query state of multiple applications in a single go
*/
/*
INPROC - transport within a process (between threads, modules etc.) 线程
IPC - transport between processes on a single machine 进程
TCP - network transport via TCP 网络TCP
WS - websockets over TCP websockets TCP
*/
//ipc:// 标识用于多进程通信,后面的sky_test是我自己命名,可以随意命名
char *url = "ipc://sky_test";
int server_sock_init(int *sock)
{
*sock = nn_socket (AF_SP, NN_PAIR);
if (*sock < 0) {
printf("create server sock failed\r\n");
return 1;
}
if (nn_bind(*sock, url) < 0) {
printf("bind server sock failed\r\n");
return 1;
}
printf("server socket init success...\r\n");
return 0;
}
int client_sock_init(int *sock)
{
*sock = nn_socket (AF_SP, NN_PAIR);
if (*sock < 0) {
printf("create server sock failed\r\n");
return 1;
}
if (nn_connect(*sock, url) < 0) {
printf("bind server sock failed\r\n");
return 1;
}
printf("client socket init success...\r\n");
return 0;
}
void child_process_test()
{
int c_sock;
char *tx_msg = "Hello Main Process";
if (0 != client_sock_init(&c_sock)) {
return;
}
while (1) {
//发送信息到主进程客户端
while (1) {
size_t len = strlen (tx_msg) + 1;
if (nn_send(c_sock, tx_msg, len, 0) < 0) {
printf("Thread Send Msg Failed\r\n");
usleep(500000);
continue;
}
break;
}
while (1) {
//接收主进程客户端信息
char *rx_msg = NULL;
int result = nn_recv(c_sock, &rx_msg, NN_MSG,NN_DONTWAIT);
if (result > 0) {
printf("Child Process Recieve: %s\r\n", rx_msg);
nn_freemsg (rx_msg);
break;
}
usleep(200000);
}
}
}
void main_process_test()
{
int s_sock;
char *tx_msg = "Hi Child Process Test";
if (0 != server_sock_init(&s_sock)) {
return;
}
sleep(1);
while (1) {
while (1) {
//接收子进程客户端信息
char *rx_msg = NULL;
int result = nn_recv(s_sock, &rx_msg, NN_MSG,NN_DONTWAIT);
if (result > 0) {
printf("Main Recieve: %s\r\n", rx_msg);
nn_freemsg (rx_msg);
break;
}
usleep(200000);
}
//发送信息到子进程客户端
while (1) {
size_t len = strlen (tx_msg) + 1;
if (nn_send(s_sock, tx_msg, len, 0) < 0) {
printf("Main Send Msg Failed\r\n");
usleep(500000);
continue;
}
break;
}
}
}
int main()
{
pid_t fpid;
fpid = fork();
if (fpid < 0) {
printf("fork failed\r\n");
return 1;
} else if (fpid == 0) {
//子进程
child_process_test();
} else {
//主进程
main_process_test();
}
return 0;
}
编译运行:
//我的c文件名称nanomsg_ipc.c,编译时记得加上-lnanomsg
gcc -o nanomsg_ipc nanomsg_ipc.c -lnanomsg
运行结果:
总结:
这样,我们就实现了多进程之间通信,这对于多进程编程来说,传输数据就非常方便了,对于实际编程过程中会有很大的帮助。