使用Unix域套接字实现进程间通讯
闲了整理了一下以前用到的例子,贴出来与大伙分享一下^_^
- /*
- domain_socket.h
- @Author: duanjigang @2006-4-11
- @Desp: declaratin of methods used for unix-domain-socket communication
- */
- #ifndef _H_
- #define _H_
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/un.h>
- #include <sys/socket.h>
- #define MSG_SIZE 1024
- int init_send_socket(struct sockaddr_un * addr,char * path)
- {
- int sockfd,len;
- sockfd=socket(AF_UNIX,SOCK_DGRAM,0);
- if(sockfd<0)
- {
- exit(1);
- }
- bzero(addr,sizeof(struct sockaddr_un));
- addr->sun_family=AF_UNIX;
- strcpy(addr->sun_path,path);
- return sockfd;
- }
- int init_recv_socket(char * path)
- {
- int sockfd,len;
- struct sockaddr_un addr;
- sockfd=socket(AF_UNIX,SOCK_DGRAM,0);
- if(sockfd<0)
- {
- return -1;
- }
- bzero(&addr,sizeof(struct sockaddr_un));
- addr.sun_family = AF_UNIX;
- strcpy(addr.sun_path, path);
- unlink(path);
- len = strlen(addr.sun_path) + sizeof(addr.sun_family);
- if(bind(sockfd,(struct sockaddr *)&addr,len)<0)
- {
- return -1;
- }
- return sockfd;
- }
- int receive_from_socket(int sockfd, char msg[])
- {
- int n;
- memset(msg, 0, MSG_SIZE);
- n=recvfrom(sockfd, msg, MSG_SIZE, 0, NULL, NULL);
- if(n<=0)
- {
- return -1;
- }
- msg[n]=0;
- return n;
- }
- int send_to_socket(int sockfd, char msg[], const struct sockaddr_un * addr)
- {
- int len;
- len = strlen(addr->sun_path)+sizeof(addr->sun_family);
- sendto(sockfd, msg, strlen(msg), 0, (struct sockaddr*)addr,len);
- return 1;
- }
- #endif
复制代码
一个调用的例子
- /*
- main.c
- @Author: duanjigang @ 2006-4-11
- @Desp: Two processes communicate with unix domain socket
- */
- #include "domain_socket.h"
- #define PATH "/home/useless"
- /*
- 进程间通过域进行通讯-举例:父子进程,一个发送,一个接收
- */
- int main(void)
- {
- int pid;
- /*
- 子进程用于发送消息
- */
- if((pid = fork()) == 0)
- {
- int fd, counter = 0;
- char send_buffer[MSG_SIZE];
- struct sockaddr_un addr;
- if( (fd = init_send_socket(&addr, PATH)) > 0)
- while(1)
- {
- memset(send_buffer, 0 , MSG_SIZE);
- /*
- 防止计数器越界,所以做一个复位判断
- */
- sprintf(send_buffer,"message for %d times",
- counter++ >= 10000 ? 1 : counter);
- send_to_socket(fd, send_buffer, &addr);
- printf("Sender: %sn", send_buffer);
- sleep(1);
- }
- }/*
- 父进程用于接收消息
- */
- else
- {
- int fd;
- char recv_buffer[MSG_SIZE];
- if( (fd = init_recv_socket(PATH))> 0)
- while(1)
- {
- memset(recv_buffer, 0, MSG_SIZE);
- if(receive_from_socket(fd, recv_buffer))
- {
- printf("Receiver: %sn", recv_buffer);
- }
- }
- }
- }
复制代码
[ 本帖最后由 duanjigang 于 2006-4-11 17:13 编辑 ]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论