sve
sve

Reputation: 4356

Sockets in C: consecutive order of primitive calls

I've written basic server in C. The source code of the server is something like this:

int sfd;
...
read(sfd,...);
write(sfd,...);
...

and the client is:

int sfd;
...
write(sfd,...);
read(sfd,...);
...

What is the order in which those primitives are called? write(client), read(server), write(server), read(client). In this order? If not, is there a way we can ensure that?

Upvotes: 0

Views: 249

Answers (2)

mah
mah

Reputation: 39807

If you want to ensure a specific order you need to use a mutex or some other concurrency tool (semaphore, etc).

Unless there's more to your application than you're showing, you probably don't care about the order -- read() will block until its corresponding write() has been performed, unless you set a non-blocking option.

Upvotes: 0

Michael Mior
Michael Mior

Reputation: 28762

write and read are blocking. It doesn't matter which is called first. If you call read on the server before write on the client, then read will block until receives the appropriate number of bytes.

Upvotes: 1

Related Questions