Darren Fernando
Darren Fernando

Reputation: 23

While loop doesn't exit after writing to file in C

I'm sending a file from the client to the server. I take an input from the client, and in this case its for file transfer and after completion the client is supposed to reprompt for a new command. This is how I send a file:

Client (sends):

            size_t bytes_read = 0;
            ssize_t bytes_written = 0;
            
            
            while((bytes_read = fread(buf, 1, sizeof(buf), fp)) > 0){ 
            
                if ((bytes_written = write(sd, buf, bytes_read)) < 0){
                    printf("Error sending client file.\n");
                }
            
            }
            
            printf("bytes written: %ld\n", bytes_written);
            fclose(fp);
            }   

Server (receives):

             while((bytes_read = read(sd, buf, sizeof(buf))) > 0){ 
                    
                printf("The contents: %s", buf);
                fwrite(buf, 1, bytes_read, fp);
                printf("Done writing\n");
                
                }
                printf("The server has received the requested document.\n");
                fclose(fp);

The problem I'm having, is that the print statement printf("The server has received the requested document.\n"); is never executed which is the last statement I print before this IF statement carrying all the operations is closed. And I'm unable to enter new commands from the client because I assume its stuck in this while loop. Only when I force stop the server program, that print line is reached and then the program exits. The strange thing, is that after I force stop it I can see that the file I transferred has actually been transferred correctly. But why wont it leave this while loop?

Upvotes: 1

Views: 393

Answers (1)

Joshua
Joshua

Reputation: 43217

(need formatting on a comment, so temporary CW answer)

Only when I force stop the server program, that print line is reached and then the program exits.

(He presses ^Z shoving it into the background.)

The problem isn't in the posted code. Demonstration: add the following lines after printf:

fflush(stdout);
_exit(0);

Poof, process exits.

Upvotes: 1

Related Questions