码迷,mamicode.com
首页 > 其他好文 > 详细

域套接字代码示例(1)

时间:2015-12-27 19:02:58      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

使用socketpair可以在有亲缘关系的进程间(如父子进程)使用域套接字进行通信。

#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <iostream>

using namespace std;

int main()
{
    int sockfd[2];
    if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sockfd) < 0)
    {
        cout << "fail to create socket pair" << endl;
        return -1;
    }

    int iRet = fork();
    if (iRet < 0)
    {
        cout << "fail to fork child" << endl;
        return -1;
    }
    else if (iRet > 0)
    {
        // parent
        close(sockfd[1]);
        char acSend[] = "how are you";
        write(sockfd[0], acSend, strlen(acSend));
        char acRecv[20] = { 0 };
        read(sockfd[0], acRecv, sizeof(acRecv));
        cout << "parent recv: " << acRecv << endl;
    }
    else
    {
        // child
        close(sockfd[0]);
        char acRecv[20] = { 0 };
        read(sockfd[1], acRecv, sizeof(acRecv));
        cout << "child recv: " << acRecv << endl;
        char acSend[] = "fine, thank you";
        write(sockfd[1], acSend, strlen(acSend));
    }
    
    return 0;
}

 

域套接字代码示例(1)

标签:

原文地址:http://www.cnblogs.com/glacierh/p/5080474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!