【问题标题】:What is the correct way to listen to both UDS and TCP sockets in a `fork()` based server?在基于“fork()”的服务器中监听 UDS 和 TCP 套接字的正确方法是什么?
【发布时间】:2015-04-11 16:35:30
【问题描述】:

我正在编写一个基于fork() 的服务器,TCP 套接字是客户端与服务器的通信通道,而 UDS 套接字(数据报,如果有任何区别)是 管理的通信通道控制台与服务器。

监听这两种套接字类型的正确方法是什么?我的服务器目前看起来很像 Beej 示例中的 fork() 服务器:

while(1) {  // main accept() loop
    sin_size = sizeof their_addr;
    new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
    if (new_fd == -1) {
        perror("accept");
        continue;
    }

    inet_ntop(their_addr.ss_family,
        get_in_addr((struct sockaddr *)&their_addr),
        s, sizeof s);
    printf("server: got connection from %s\n", s);

    if (!fork()) { // this is the child process
        close(sockfd); // child doesn't need the listener
        if (send(new_fd, "Hello, world!", 13, 0) == -1)
            perror("send");
        close(new_fd);
        exit(0);
    }
    close(new_fd);  // parent doesn't need this
}

您将如何在上述代码中添加侦听和等待 UDS 套接字(已绑定)中的连接的能力。

【问题讨论】:

    标签: c sockets network-programming posix unix-socket


    【解决方案1】:

    使用 select()poll()epoll()epoll() 假设是 Linux。)

    或者使用多个线程。

    【讨论】:

    • 多线程是什么意思?我不想使用 I/O 多路复用是有原因的(教育原因)
    • 使用原线程监听一个端口,启动另一个监听另一个。
    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 2013-07-23
    • 2010-10-14
    • 2012-04-06
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多