APUE 网络IPC 习题16.3
本帖最后由 iamzhaiwei 于 2011-10-24 19:44 编辑怎么修改程序使其同时支持多个端点的服务?
我改的程序如下(主要是红色部分):
#define BUFLEN 128
#define QLEN 10
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 256
#endif
void serve(fd_set *sockfdsp, int maxsockfd)
{
int nfds;
int sockfd;
int clfd;
FILE *fp;
char buf;
for (;;)
{
if (select(maxsockfd+1, sockfdsp, NULL, NULL, NULL) > 0)
{
for (sockfd = 0; FD_ISSET(sockfd, sockfdsp); ++sockfd)
{
clfd = accept(sockfd, NULL, NULL);
if (clfd < 0)
{
syslog(LOG_ERR, "ruptimed: accept error: %s",
strerror(errno));
exit(1);
}
if ((fp = popen("/usr/bin/uptime", "r")) == NULL)
{
sprintf(buf, "error: %s\n", strerror(errno));
send(clfd, buf, strlen(buf), 0);
}
else
{
while (fgets(buf, BUFLEN, fp) != NULL)
send(clfd, buf, strlen(buf), 0);
pclose(fp);
}
close(clfd);
}
}
}
}
int main(int argc, char *argv[])
{
char *host;
int n;
struct addrinfo *ailist, *aip;
struct addrinfo hint;
int sockfd, maxsockfd;
fd_set sockfds;
int err;
if (argc != 1)
err_quit("usage: ruptimed");
#ifdef _SC_HOST_NAME_MAX
n = sysconf(_SC_HOST_NAME_MAX);
if (n < 0)
#endif
n = HOST_NAME_MAX;
host = malloc(n);
if (host == NULL)
err_sys("malloc error");
if (gethostname(host, n) < 0)
err_sys("gethostname errno");
FD_ZERO(&sockfds);
maxsockfd = 0;
daemonize("ruptimed");
hint.ai_flags = AI_CANONNAME;
hint.ai_family = 0;
hint.ai_socktype = 0;
hint.ai_protocol = 0;
hint.ai_addrlen = 0;
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
if ((err = getaddrinfo(host, "ruptime", &hint, &ailist)) != 0)
{
syslog(LOG_ERR, "ruptimed: getaddrinfo error %s", gai_strerror(err));
exit(1);
}
for (aip = ailist; aip != NULL; aip = aip->ai_next)
{
if ((sockfd = initserver(SOCK_STREAM, aip->ai_addr, aip->ai_addrlen,
QLEN)) >= 0)
{
FD_SET(sockfd, &sockfds);
maxsockfd = (sockfd > maxsockfd) ? sockfd : maxsockfd;
}
}
if (maxsockfd > 0)
{
serve(&sockfds, maxsockfd);
exit(0);
}
exit(1);
}
运行客户端程序后,cpu占到95%多,没有返回结果。
等候高人解答。 没有人回答吗?自己顶 LZ这个问题解决了? for (sockfd = 0; FD_ISSET(sockfd, sockfdsp); ++sockfd)有错吧
页:
[1]