gpt4 book ai didi

c - 在基于 `fork()` 的服务器中监听 UDS 和 TCP 套接字的正确方法是什么?

转载 作者:行者123 更新时间:2023-11-30 15:21:22 25 4
gpt4 key购买 nike

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

监听两种套接字类型的正确方法是什么?我的服务器目前看起来与 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 套接字(已绑定(bind))中的连接的功能。

最佳答案

使用select()poll()epoll()(epoll()确实假设Linux。)

或者使用多线程。

关于c - 在基于 `fork()` 的服务器中监听 UDS 和 TCP 套接字的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29580306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com