socket unix domain IPC的实例代码
仅供参考:
服务端:socket->bind->listen->send/recv->close
客户端:socket->bind->connect->send/recv->close
#include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<arpa/inet.h> #include<errno.h> #include<fcntl.h> #include<sys/un.h> #include<pthread.h> #include<cstring> #include<cstdio> #include<unistd.h> #include<signal.h> #definefilename"test.socket" voidsetnonblocking(intfd) { fcntl(fd,F_SETFL,fcntl(fd,F_GETFL)|O_NONBLOCK); } void*client_func(void*arg) { sleep(3); intfd=socket(AF_UNIX,SOCK_STREAM,0); setnonblocking(fd); sockaddr_unun; memset(&un,0,sizeof(un)); un.sun_family=AF_UNIX; sprintf(un.sun_path,"file_%d.socket",(int)getpid()); unlink(un.sun_path); socklen_tlen=sizeof(un); bind(fd,(sockaddr*)&un,sizeof(un)); strcpy(un.sun_path,filename); intret=connect(fd,(sockaddr*)&un,len); if(ret==-1) { printf("connectserverfailed...\n"); close(fd); returnNULL; } charbuf[256]; memset(buf,0,sizeof(buf)); strcpy(buf,"helloworld"); intn=send(fd,buf,strlen(buf)+1,0); printf("senddata,%dbytes..\n",n); sleep(5); close(fd); returnNULL; } intmain() { unlink(filename); signal(SIGPIPE,SIG_IGN); intfd=socket(AF_UNIX,SOCK_STREAM,0); intyes=1; setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes)); setnonblocking(fd); sockaddr_unun; memset(&un,0,sizeof(un)); un.sun_family=AF_UNIX; strcpy(un.sun_path,filename); bind(fd,(sockaddr*)&un,sizeof(un)); listen(fd,100); pthread_tpid; pthread_create(&pid,NULL,client_func,NULL); sockaddr_unuu; socklen_tlen=sizeof(uu); while(true) { memset(&uu,0,len); intnewfd=accept(fd,(sockaddr*)&uu,&len); if(newfd!=-1) { setnonblocking(newfd); printf("newfd=%d,path=%s\n",newfd,uu.sun_path); charbuf[512]; memset(buf,0,sizeof(buf)); intn=recv(newfd,buf,512,0); printf("recv%dbytes,contentsis%s\n",n,buf); } usleep(100000); } close(fd); return0; }
以上就是小编为大家带来的socketunixdomainIPC的实例代码全部内容了,希望大家多多支持毛票票~