当前位置: 技术问答>linux和unix
linux socket编程 accept 返回值的问题
来源: 互联网 发布时间:2016-05-07
本文导语: 这是socket 的服务端, for(i = 1; ; i++) { alen = sizeof(client); if((comfd = accept(sockfd, (struct sockaddr *)&client, &alen)) == -1) { fprintf(stdout, "%d comfd is %dn", i, comfd); exit(1); perror("accept err...
这是socket 的服务端,
for(i = 1; ; i++)
{
alen = sizeof(client);
if((comfd = accept(sockfd, (struct sockaddr *)&client, &alen)) == -1)
{
fprintf(stdout, "%d comfd is %dn", i, comfd);
exit(1);
perror("accept error");
}
pid_t child;
if((child = fork()) == -1)
{
perror("fork err");
return -1;
}
if(child == 0) /*child processer*/
{
if(close(sockfd) == -1)
{
perror("ti client failed close sockfd");
return -1;
}
fprintf(stdout, "%d client connectedt", i);
buf [1]= 'a';buf[1] = 'b';buf[2]='';
recv(comfd, buf, BUFLEN, 0);
fprintf(stdout, "receive: %st", buf);
send(comfd, buf, sizeof(buf), 0);
}
if(close(comfd) == -1)
{
perror("failed to close i client comfd");
return -1;
}
}
当客户端向服务端发送hello world时,结果如下:
1 client connected receive: hello world 2 comfd is -1
2 client connected receive: hello world 3 comfd is -1
3 client connected receive: hello world 4 comfd is -1
4 client connected receive: hello world 5 comfd is -1
for(i = 1; ; i++)
{
alen = sizeof(client);
if((comfd = accept(sockfd, (struct sockaddr *)&client, &alen)) == -1)
{
fprintf(stdout, "%d comfd is %dn", i, comfd);
exit(1);
perror("accept error");
}
pid_t child;
if((child = fork()) == -1)
{
perror("fork err");
return -1;
}
if(child == 0) /*child processer*/
{
if(close(sockfd) == -1)
{
perror("ti client failed close sockfd");
return -1;
}
fprintf(stdout, "%d client connectedt", i);
buf [1]= 'a';buf[1] = 'b';buf[2]='';
recv(comfd, buf, BUFLEN, 0);
fprintf(stdout, "receive: %st", buf);
send(comfd, buf, sizeof(buf), 0);
}
if(close(comfd) == -1)
{
perror("failed to close i client comfd");
return -1;
}
}
当客户端向服务端发送hello world时,结果如下:
1 client connected receive: hello world 2 comfd is -1
2 client connected receive: hello world 3 comfd is -1
3 client connected receive: hello world 4 comfd is -1
4 client connected receive: hello world 5 comfd is -1
|
因为你的子进程里没有退出也进入循环里了。
comfd is -1是你子进程输出的,你子进程里把sockfd关掉了,所以子进程里accept会失败,从面输出,输出的时候加上进程号就一目了然了。
comfd is -1是你子进程输出的,你子进程里把sockfd关掉了,所以子进程里accept会失败,从面输出,输出的时候加上进程号就一目了然了。