免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1047 | 回复: 0
打印 上一主题 下一主题

unix socket [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-12-15 01:54 |只看该作者 |倒序浏览

Unix域套接字是通过套接字API实现的简单的协议族。实际上它并不代表一个网络协议;它只能连接到同一台机器上的套接字。它提供了灵活的IPC机制。它的地址是它所在的文件系统的路径名,创建之后套接字就和路径名绑定在一起。用来表示Unix域地址的套接字文件能够使用stat()但是不能通过open()打开,而且应该使用套接字API对它进行操作。
Unix域套接字是面向连接的,每个套接字的连接都建立了一个新的通讯信道。服务器可能同时处理许多连接,但对于每个连接都有不同的文件描述符。这个属性使Unix域套接字能够比命名管道更好的适应IPC任务。
.
在一个终端运行服务器,然后在另一个终端(在相同目录下)运行客户端。当从客户端输入一行时,数据将通过套接字送到服务器。当退出客户端,服务器将等待另外一个连接。还可以通过客户端程序的重定向输入来传送文件,cat uclient.c | ./uclient 或 ./uclient
#include
#include
#include
#include "sockutil.h"          /* some utility functions */
int main(void) {
    struct sockaddr_un address;
    int sock, conn;
    size_t addrLength;
    if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) = 0) {
        printf("---- getting data\n");
        copyData(conn, 1);
        printf("---- done\n");
        close(conn);
    }
    if (conn
#include
#include
#include "sockutil.h"          /* some utility functions */
int main(void) {
    struct sockaddr_un address;
    int sock;
    size_t addrLength;
    if ((sock = socket(PF_UNIX, SOCK_STREAM, 0))
#include
#include
#include "sockutil.h"
/* issue an error message via perror() and terminate the program */
void die(char * message) {
    perror(message);
    exit(1);
}
/* Copies data from file descriptor 'from' to file descriptor
   'to' until nothing is left to be copied. Exits if an error
   occurs. This assumes both from and to are set for blocking
   reads and writes. */
void copyData(int from, int to) {
    char buf[1024];
    int amount;
   
    while ((amount = read(from, buf, sizeof(buf))) > 0) {
        if (write(to, buf, amount) != amount) {
            die("write");
            return;
        }
    }
    if (amount

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/95172/showart_2121493.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP