我编写了一个服务器程序,它只接受来自客户端的连接。为此,接受函数处于无限循环中。但是当它执行在循环没有被打印之前打印的消息时。我的代码是:
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
void main()
{
int sock,bind_sock,lis_sock,cli_sock,addr_len;
struct sockaddr_in addr,cli_addr;
if ((sock=socket(AF_INET,SOCK_STREAM,0))<0)
printf("\nsocket error");
else
printf("socket");
addr.sin_family=AF_INET;
addr.sin_port=htons(5012);
addr.sin_addr.s_addr=htonl(INADDR_ANY);
if((bind_sock=bind(sock,(struct sockaddr *)&addr,sizeof(addr)))<0)
printf("\nBound error");
else
printf("Bound");
if((lis_sock=listen(sock,10))<0)
printf("\nlisten error");
else
printf("listen\nwaiting for connection" );
while(1)
{
addr_len=sizeof(cli_addr);
cli_sock=accept(sock,(struct sockaddr *)&cli_addr,&addr_len);
if(cli_sock<0)
printf("\nConnetion Error\n");
else
printf("conneted\n");
}
,它给出的输出是:
]$ ./a.out
socketBoundlisten