Linux IPC技术简介(ipclinux)

IPC(Inter-process communication),指进程间通信,形象地理解即为进程之间传递消息进行通信的技术。Linux下有sockets、pipes、shared memory、message queues以及semaphores五种IPC技术,常用的IPC技术包括Unix domain sockets和named pipes,我们一起来看一看这些技术的使用。

1. Unix domain sockets

Unix domain sockets是最常用的IPC技术,通常被称为AF_UNIX sockets。它基于BSD socket实现,是操作系统的本地套接字,可以通过文件系统访问。它可以实现TCP/IP协议无关的进程间通信,应用程序可以使用它来通信,而无需要一个网络连接,速度比类似网络通信技术要快得多。Unix domain sockets只能在同一台机器上使用。若使用这种方式,它会为每个活动连接创建一个虚拟文件(文件句柄),这样服务器就可以知道客户端的详细情况,以此来区分客户端与客户端之间的通信。

实际使用代码如下:

Server:

#include

#include

#include

int main()

{

int sockfd;

struct sockaddr_un addr;

sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

if (sockfd

printf(“Error creating socket.\n”);

exit(-1);

}

memset(&addr, 0, sizeof(struct sockaddr_un));

addr.sun_family = AF_UNIX;

strcpy(addr.sun_path, “/tmp/socket_server”);

if (bind(sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un))

printf(“Error binding socket.\n”);

exit(-1);

}

// …

return 0;

}

Client:

#include

#include

#include

int main()

{

int sockfd;

struct sockaddr_un addr;

sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

if (sockfd

printf(“Error creating socket.\n”);

exit(-1);

}

memset(&addr, 0, sizeof(struct sockaddr_un));

addr.sun_family = AF_UNIX;

strcpy(addr.sun_path, “/tmp/socket_server”);

if (connect(sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un))

printf(“Error connecting socket.\n”);

exit(-1);

}

// …

return 0;

}

2. named pipes

Named pipes也常被称为FIFOs(First-In-First-Out),是一种特殊的文件类型,Linux它实现了有名管道,也是一种IPC技术,它可以实现不同进程之间的通信,用户可以将它看成一个普通文件,但是它拥有FIFO文件这一特性。Named pipes可以实现进程间通信,也实现进程与用户之间的通信,用户可以向另一个管道端输入信息,而另外一个进程可以从管道读取这些数据。

实际使用代码如下:

向管道写入数据:

#include

#include

#include

#include

int main(){

int fd;

char *myfifo = “/tmp/myfifo”;

char str[BUFSIZ];

mkfifo(myfifo, 0666);

fd = open(myfifo, O_WRONLY);

strcpy(str, “Hello fifo!”);

write(fd, str, strlen(str) + 1);

close(fd);

unlink(myfifo);

return 0;

}

从管道读取数据:

#include

#include

#include

#include

int main(){

int fd;

char *myfifo = “/tmp/myfifo”;

char str[BUFSIZ];

fd = open(myfifo, O_RDONLY);

read(fd, str, BUFSIZ);

printf(“Read: %s\n”,str);

close(fd);

return 0;

}

总而言之,Linux下提供了sockets、pipes、shared memory、message queues以及semaphores五种IPC技术,它们都可以用于实现多进程通信,相比网络通信,IPC可以大大降低程序模块之间的耦合度,这对应用程序的的设计是非常有帮助的。


数据运维技术 » Linux IPC技术简介(ipclinux)