在unix文件通信中,如果设置了
UNIX_
ABSTRACT为1,那么unix通信文件
不会在路径目录下显示出来,
如果设置
UNIX_
ABSTRACT为0,那么unix通信文件将会在路径目录下显示[luther.gliethttp]
头文件unix_abstract.h
unix server源码
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include "unix_abstract.h"
#define DBG_LOG(msg...) printf(msg)
int accept_client(int listen_fd);
int main(void)
{
int listen_fd;
size_t path_len;
struct sockaddr_un addr;
char *path = "./luther.gliethttp";
if ((listen_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
DBG_LOG("socket: %s\n", strerror(errno));
exit(-1);
}
memset(&addr, '\0', sizeof (addr));
addr.sun_family = AF_UNIX;
path_len = strlen (path);
#if UNIX_ABSTRACT
addr.sun_path[0] = '\0';
path_len++;
strncpy(&addr.sun_path[1], path, path_len);
#else
strncpy(&addr.sun_path[0], path, path_len);
unlink(path);
#endif
if (bind(listen_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
DBG_LOG("bind: %s\n", strerror(errno));
exit(-1);
}
if (listen (listen_fd, 30) < 0) {
DBG_LOG("listen: %s\n", strerror(errno));
exit(-1);
}
DBG_LOG("OK\n");
for (;;) {
int client_fd;
if ((client_fd = accept_client(listen_fd)) < 0) {
DBG_LOG("accept_client: %s\n", strerror(errno));
}
DBG_LOG("client=%d\n", client_fd);
sleep(1);
}
return 0;
}
int accept_client(int listen_fd)
{
int client_fd;
struct sockaddr addr;
socklen_t addrlen;
addrlen = sizeof (addr);
retry:
client_fd = accept(listen_fd, &addr, &addrlen);
if (client_fd < 0) {
if (errno == EINTR)
goto retry;
}
return client_fd;
}
|
client端源码
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "unix_abstract.h"
#define DBG_LOG(msg...) printf(msg)
int main(void)
{
int unix_fd;
size_t path_len;
struct sockaddr_un addr;
char *path = "./luther.gliethttp";
if ((unix_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
DBG_LOG("socket: %s\n", strerror(errno));
exit(-1);
}
memset(&addr, '\0', sizeof (addr));
addr.sun_family = AF_UNIX;
path_len = strlen (path);
#if UNIX_ABSTRACT
addr.sun_path[0] = '\0';
path_len++;
strncpy(&addr.sun_path[1], path, path_len);
#else
strncpy(&addr.sun_path[0], path, path_len);
#endif
if (connect(unix_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
DBG_LOG("connect: %s\n", strerror(errno));
exit(-1);
}
DBG_LOG("OK\n");
for (;;) {
char buf[10];
static int serial = 0;
sprintf(buf, "%d", serial++);
write(unix_fd, buf, strlen(buf));
sleep(1);
}
return 0;
}
int accept_client(int listen_fd)
{
int client_fd;
struct sockaddr addr;
socklen_t addrlen;
addrlen = sizeof (addr);
retry:
client_fd = accept(listen_fd, &addr, &addrlen);
if (client_fd < 0) {
if (errno == EINTR)
goto retry;
}
return client_fd;
}
|
luther@gliethttp:~$ gcc -o unix_socket unix_socket.c
luther@gliethttp:~$ gcc -o unix_socket_client unix_socket_client.c
luther@gliethttp:~$ ./unix_socket
OK
client=4
luther@gliethttp:~$ ./unix_socket_client
OK
阅读(1657) | 评论(0) | 转发(0) |