user3032010
user3032010

Reputation: 47

message not printed while using infinite loop

I have written a program of server that just accepts the connection from client. For that the accept function in an infinite loop. but when it executes the message printed just before the loop does not get printed . My Code is:

     #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");

    }

} and the output it gives is:

    ]$ ./a.out
   socketBoundlisten

Upvotes: 0

Views: 100

Answers (4)

Koushik Shetty
Koushik Shetty

Reputation: 2176

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).

Upvotes: 0

Chiara Hsieh
Chiara Hsieh

Reputation: 3393

Try do this before printf.

setvbuf (stdout, NULL, _IONBF, 0);

Upvotes: 1

Aniket Inge
Aniket Inge

Reputation: 25705

chances are your "waiting for connection" may be buffered and may print when your client connects. Did you try connecting a client and seeing the output?

Also try this:

if((lis_sock=listen(sock,10))<0)
        printf("\nlisten error");
else
        printf("listen\nwaiting to connect");

Upvotes: 1

Pradheep
Pradheep

Reputation: 3819

printf is line terminated so add \n to the end and check the output .example

        printf("conneted \n");

Upvotes: 2

Related Questions