问题描述
- 多客户socket出现fork: Resource temporarily unavailable
-
server端代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "multiple_socket.h"int main()
{
int server_sockfd,client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t server_len, client_len;/* Create an unnamed socket for server */ server_sockfd = socket(AF_INET, SOCK_STREAM, 0); /* Name the socket */ server_addr.sin_family = AF_INET; server_addr.sin_port = SIN_PORT; server_addr.sin_addr.s_addr = inet_addr(LOOPBACK); server_len = sizeof(server_addr); bind(server_sockfd, (struct sockaddr *)&server_addr, server_len); /* Create a connection queue & wait for clients */ listen(server_sockfd, SOCKET_QUEUE_SIZE); signal(SIGCHLD, SIG_IGN); while(1) { char ch; if(0 == fork()) { /* Accept a connection */ client_len = sizeof(server_addr); client_fd = accept(server_sockfd, (struct sockaddr *)&client_addr, &client_len); read(client_fd, &ch, 1); sleep(SLEEP_TIME); ch++; write(client_fd, &ch, 1); close(client_fd); exit(0); } } return 0;
}
解决方案
你这样循环的创建子进程,导致资源不足,所以报这样的错误,应该在accept之后fork
解决方案二:
这样等待链接资源消耗太狠了,应该链接成功一路开启一个子进程才合理,建议还是不要用多进程,还是多线程更为舒服用起来
时间: 2024-10-28 04:15:27