Socket Api 原本是为网络通讯设计的,但后来在socket 的框架上发展出一种IPC机制, 他式可靠的通信, 他只是将应用层数据从一个进程拷贝到另一个进程。
服务器代码:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <c#type.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <string.h>
#define MAXLINE 80
int main(void)
{
int unix_fd = Socket(AF_UNIX, SOCK_STREAM, 0);
int connfd;
int cliaddr_len;
struct sockaddr_un server_addr, cliaddr;
server_addr.sun_family = AF_UNIX;
unlink("socket.file");
strcpy(server_addr.sun_path, "socket.file");
Bind(unix_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
Listen(unix_fd, 20);
printf("server start ..../n ");
while (1)
{
cliaddr_len = sizeof(cliaddr);
connfd = Accept(unix_fd, (struct sockaddr *)&cliaddr, &cliaddr_len);
char buf[MAXLINE];
int n = Read(connfd, buf, MAXLINE);
printf("recerve the message: %s/n" , buf);
}
Close(connfd);
}
客户端代码:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/un.h>
#include <stddef.h>
#define MAXLINE 80
int main(void)
{
int unix_fd = Socket(AF_UNIX, SOCK_STREAM, 0);
int len;
char buf[MAXLINE];
struct sockaddr_un server_addr;
int n;
server_addr.sun_family = AF_UNIX;
strcpy(server_addr.sun_path, "socket.file");
len = offsetof(struct sockaddr_un, sun_path) + strlen("socket.file");
//stycpy(server_addr.sun_path, "socket.file");
//Bind(unix_fd, (struct sockaddr *)&servaddr, sizeof(servaddr));
Connect(unix_fd, (struct sockaddr *)&server_addr, len);
while (fgets(buf, MAXLINE, stdin) != NULL)
{
Write(unix_fd, buf, strlen(buf));
n = Read(unix_fd, buf, MAXLINE);
if (n == 0)
printf("the other side has been closed: /n");
else
Write(STDOUT_FILENO, buf, n);
//printf("buf: %s/n", buf);
}
Close(unix_fd);
}