【发布时间】: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