Brandon Ling
Brandon Ling

Reputation: 3919

Unusual Server behavior with sockets

When writing my server code I have this line:

newsockfd =  accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);

When I run the program I get no errors, but the program just freezes, and I put a print statement at the first line of the main() (so it should run before anything runs) but the print statement never gets executed.

This line of code is definitely the problem because once I comment it out, my print statements work.

What might create such bizarre behavior?
(I'm not allowed to post homework code, so unfortunately I can't post all of it)

Upvotes: 0

Views: 64

Answers (3)

Mike
Mike

Reputation: 49473

The other option for you is to fflush() the stdout, which will force it to "print" anything buffered regardless of the '\n':

printf("print this now!");
fflush(stdout);

Upvotes: 1

Jamey Sharp
Jamey Sharp

Reputation: 8501

Since this was apparently the answer, I'll write it here: If your printf format strings don't end with "\n", then they'll be buffered until either you do print a newline or your program exits. (I'm simplifying a bit.) Since your accept call stopped your program after that output was buffered, you couldn't see the output even though the printf calls were working fine.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182837

It's waiting for a connection. That's the purpose of the accept function.

Upvotes: 0

Related Questions