我在处理僵尸程序时遇到了一些麻烦。我编写了一个简单的服务器来创建玩家之间的tic tac脚趾匹配。我使用select()在多个连接的客户端之间进行多路复用。每当有两个客户端时,服务器将分叉另一个进程,该进程将执行一个匹配仲裁程序。
问题是select()块。因此,如果有一个匹配仲裁程序作为子进程运行并退出,那么如果没有传入连接,父进程就不会等待子进程,因为select()是阻塞的。
我这里有我的代码,抱歉,因为它很混乱。
while(1) {
if (terminate)
terminate_program();
FD_ZERO(&rset);
FD_SET(tcp_listenfd, &rset);
FD_SET(udpfd, &rset);
maxfd = max(tcp_listenfd, udpfd);
/* add child connections to set */
for (i = 0; i < MAXCLIENTS; i++) {
sd = tcp_confd_lst[i];
if (sd > 0)
FD_SET(sd, &rset);
if (sd > maxfd)
maxfd = sd;
}
/* Here select blocks */
if ((nready = select(maxfd + 1, &rset, NULL, NULL, NULL)) < 0) {
if (errno == EINTR)
continue;
else
perror("select error");
}
/* Handles incoming TCP connections */
if (FD_ISSET(tcp_listenfd, &rset)) {
len = sizeof(cliaddr);
if ((new_confd = accept(tcp_listenfd, (struct sockaddr *) &cliaddr, &len)) < 0) {
perror("accept");
exit(1);
}
/* Send connection message asking for handle */
writen(new_confd, handle_msg, strlen(handle_msg));
/* adds new_confd to array of connected fd's */
for (i = 0; i < MAXCLIENTS; i++) {
if (tcp_confd_lst[i] == 0) {
tcp_confd_lst[i] = new_confd;
break;
}
}
}
/* Handles incoming UDP connections */
if (FD_ISSET(udpfd, &rset)) {
}
/* Handles receiving client handles */
/* If client disconnects without entering their handle, their values in the arrays will be set to 0 and can be reused. */
for (i = 0; i < MAXCLIENTS; i++) {
sd = tcp_confd_lst[i];
if (FD_ISSET(sd, &rset)) {
if ((valread = read(sd, confd_handle, MAXHANDLESZ)) == 0) {
printf("Someone disconnected: %s\n", usr_handles[i]);
close(sd);
tcp_confd_lst[i] = 0;
usr_in_game[i] = 0;
} else {
confd_handle[valread] = '\0';
printf("%s\n", confd_handle); /* For testing */
fflush(stdout);
strncpy(usr_handles[i], confd_handle, sizeof(usr_handles[i]));
for (j = i - 1; j >= 0; j--) {
if (tcp_confd_lst[j] != 0 && usr_in_game[j] == 0) {
usr_in_game[i] = 1; usr_in_game[j] = 1;
if ((child_pid = fork()) == 0) {
close(tcp_listenfd);
snprintf(fd_args[0], sizeof(fd_args[0]), "%d", tcp_confd_lst[i]);
snprintf(fd_args[1], sizeof(fd_args[1]), "%d", tcp_confd_lst[j]);
execl("nim_match_server", "nim_match_server", usr_handles[i], fd_args[0], usr_handles[j], fd_args[1], (char *) 0);
}
close(tcp_confd_lst[i]); close(tcp_confd_lst[j]);
tcp_confd_lst[i] = 0; tcp_confd_lst[j] = 0;
usr_in_game[i] = 0; usr_in_game[j] = 0;
}
}
}
}
}
}是否有一种方法允许在select()阻塞时等待运行?最好没有信号处理,因为它们是异步的。
编辑:实际上,我发现select有一个timeval数据结构,我们可以指定超时。用这个是个好主意吗?
发布于 2015-03-25 00:27:26
如果您只想防止僵尸进程,可以设置一个SIGCHLD信号处理程序。如果要真正等待返回状态,可以从信号处理程序将字节写入管道(非阻塞,以防万一),然后在select循环中读取这些字节。
有关如何处理SIGCHLD,请参见handler.html --您想要做类似于while (waitpid((pid_t)(-1), 0, WNOHANG) > 0) {}的事情
也许最好的方法是将一个字节从SIGCHLD信号处理程序发送到主select循环(非阻塞,以防万一),并在可以从管道读取字节时在select循环中执行waitpid循环。
您还可以使用signalfd文件描述符来读取SIGCHLD信号,尽管这只在Linux上有效。
发布于 2015-03-25 00:41:39
我认为你的选择是:
https://stackoverflow.com/questions/29245397
复制相似问题