1. 用途
套接字可以用于网络通信,也可以用于本机内的进程通信。由于本机内进程的IP地址都相同,因此只需要进程号来确定通信的双方。非网络通信套接字在Linux环境中的应用很多,最典型的就是Linux的桌面系统——Xserver,其就是使用非网络套接字的方法进行进程之间的通信的。
2. 用例
源码:
#include <sys/types.h> #include <sys/socket.h> #include <stdlib.h> #include <stdio.h> int main () { int fd[2]; int r = socketpair( AF_UNIX, SOCK_STREAM, 0, fd ); if ( r < 0 ) { perror( "socketpair()" ); exit( 1 ); } if ( fork() ) { /* Parent process: echo client */ int val = 0; close( fd[1] ); while ( 1 ) { sleep( 1 ); ++val; printf( "Sending data: %d\n", val ); write( fd[0], &val, sizeof(val) ); read( fd[0], &val, sizeof(val) ); printf( "Data received: %d\n", val ); } } else { /* Child process: echo server */ int val; close( fd[0] ); while ( 1 ) { read( fd[1], &val, sizeof(val) ); ++val; write( fd[1], &val, sizeof(val) ); } } }
运行结果:
$ make test cc test.c -o test $ ./test Sending data: 1 Data received: 2 Sending data: 3 Data received: 4 Sending data: 5 Data received: 6 Sending data: 7 Data received: 8 Sending data: 9 Data received: 10 Sending data: 11 Data received: 12 Sending data: 13 Data received: 14