0

我编写了一个服务器程序,它只接受来自客户端的连接。为此,接受函数处于无限循环中。但是当它执行在循环没有被打印之前打印的消息时。我的代码是:

     #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
4

4 回答 4

2

printf 是行终止的,因此将 \n 添加到末尾并检查输出 .example

        printf("conneted \n");
于 2013-03-22T07:14:54.923 回答
1

您的“等待连接”可能会被缓冲并在您的客户端连接时打印。您是否尝试连接客户端并查看输出?

也试试这个:

if((lis_sock=listen(sock,10))<0)
        printf("\nlisten error");
else
        printf("listen\nwaiting to connect");
于 2013-03-22T07:21:56.480 回答
1

尝试在 printf 之前执行此操作。

setvbuf (stdout, NULL, _IONBF, 0);

于 2013-03-22T07:32:15.797 回答
0

kanika you mentioned that fflush(stdout) has solved so as aniket mentioned it was being buffered. 2 possible solutions for buffered printf

1) use fflush(stdout) because stdout is buffered and prints whats after newline.

OR

2)disable buffering by setbuf(stdout,NULL).(or may be setvbuf).

于 2013-03-22T07:47:05.537 回答