下面是使用域套接字进行进程间通信的典型代码。
客户端代码:
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/un.h> #include <iostream> #include <string.h> #include <stdio.h> using namespace std; int main(int argc, char *argv[]) { if (argc != 2) { cout << "usage: " << argv[1] << " message" << endl; return -1; } int iSockFd = socket(AF_UNIX, SOCK_DGRAM, 0); if (iSockFd < 0) { cerr << "fail to create socket" << endl; return -1; } sockaddr_un oAddr; memset(&oAddr, 0, sizeof(oAddr)); oAddr.sun_family = AF_UNIX; strncpy(oAddr.sun_path, tmpnam(NULL), sizeof(oAddr.sun_path) - 1); if (bind(iSockFd, (sockaddr *)&oAddr, sizeof(oAddr)) < 0) { cerr << "fail to bind" << endl; return -1; } sockaddr_un oSvrAddr; memset(&oSvrAddr, 0, sizeof(oSvrAddr)); oSvrAddr.sun_family = AF_UNIX; strncpy(oSvrAddr.sun_path, "unix_socket", sizeof(oSvrAddr.sun_path) - 1); sendto(iSockFd, argv[1], strlen(argv[1]), 0, (sockaddr *)&oSvrAddr, sizeof(oSvrAddr)); socklen_t iAddrLen = sizeof(oSvrAddr); char acRecvBuf[100]; ssize_t iRecvLen = recvfrom(iSockFd, acRecvBuf, sizeof(acRecvBuf), 0, (sockaddr *)&oSvrAddr, &iAddrLen); if (iRecvLen < 0) { cerr << "fail to recv" << endl; return -1; } acRecvBuf[iRecvLen] = 0; cout << "client recv: " << acRecvBuf << endl; return 0; }
服务器代码:
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/un.h> #include <iostream> using namespace std; int main() { int iSockFd = socket(AF_UNIX, SOCK_DGRAM, 0); if (iSockFd < 0) { cerr << "fail to create socket" << endl; return -1; } unlink("unix_socket"); sockaddr_un oAddr; memset(&oAddr, 0, sizeof(oAddr)); oAddr.sun_family = AF_UNIX; strcpy(oAddr.sun_path, "unix_socket"); if (bind(iSockFd, (sockaddr *)&oAddr, sizeof(oAddr)) < 0) { cerr << "fail to bind" << endl; return -1; } sockaddr_un oClientAddr; char acBuf[100]; while (true) { socklen_t iAddrLen = sizeof(oClientAddr); ssize_t iRecvLen = recvfrom(iSockFd, acBuf, sizeof(acBuf), 0, (sockaddr *)&oClientAddr, &iAddrLen); if (iRecvLen < 0) { cerr << "fail to recv" << endl; continue; } acBuf[iRecvLen] = 0; cout << "server recv: " << acBuf << ", client addr: " << oClientAddr.sun_path << endl; sendto(iSockFd, acBuf, iRecvLen, 0, (sockaddr *)&oClientAddr, iAddrLen); } return 0; }