Note that there are some explanatory texts on larger screens.

plurals
  1. POoutput to connection request is not atomic
    primarykey
    data
    text
    <p>I have created a socket and I am trying to accept the connection. Everything works fine. But, the output is confusing me about how the following code works.</p> <pre><code> // this a server program #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;assert.h&gt; #include &lt;string.h&gt; #include &lt;sys/stat.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/socket.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/un.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;errno.h&gt; #include &lt;wait.h&gt; #define LISTENQ (1024) int main(void) { int lstn_sock, conn_sock; struct sockaddr_in my_serv; short int pnum = 4080; // create listening socket if( (lstn_sock = socket(AF_INET, SOCK_STREAM, 0)) &lt; 0) { printf("Error (socket): %s\n",strerror(errno)); exit(1); } // initialize socket address memset( &amp;my_serv, 0, sizeof(my_serv) ); my_serv.sin_family = AF_INET; my_serv.sin_addr.s_addr = INADDR_ANY; my_serv.sin_port = htons(pnum); // associate address with socket. if( bind(lstn_sock, (struct sockaddr *) &amp;my_serv, sizeof(my_serv)) &lt; 0){ printf("Error (bind): %s\n",strerror(errno)); exit(1); } //printf("lstn_sock: %d\n",lstn_sock); // start listening to socket if( listen(lstn_sock, LISTENQ) &lt; 0){ printf("Error (listen): %s\n",strerror(errno)); exit(1); } // make it a daemon while(1){ // retrieve connect request and connect if( (conn_sock = accept(lstn_sock, NULL, NULL)) &lt; 0){ printf("Error (accept): %s\n",strerror(errno)); exit(1); } printf("The server says hi!\n"); // close connected socket if( close(conn_sock) &lt; 0){ printf("Error (close): %s\n",strerror(errno)); exit(1); } } return 0; } </code></pre> <p>@ubuntu:$ ./my_code &amp; @ubuntu:$ telnet localhost 4080</p> <p>Following are the 2 different output from the above code:<br> <strong>Output1</strong><br> Trying ::1...<br> Trying 127.0.0.1..<br> Connected to localhost.<br> Escape character is '^]'.<br> The server says hi!<br> Connection closed by foreign host. </p> <p><strong>Output2</strong><br> Trying ::1...<br> Trying 127.0.0.1..<br> The server says hi!<br> Connected to localhost.<br> Escape character is '^]'.<br> Connection closed by foreign host. </p> <p>Could someone please explain the reason for the movement of "The server says hi!"<br> in the output.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload