TCP trashing data on application close

I am using c to send data to a socket with the following commands:

socket = socket(AF_INET, SOCK_STREAM, ptrp->p_proto);
ioctl(socket, FIONBIO, (char *)&on);
connect(socket)
send(socket,data)
shutdown(socket, SHUT_WR);
recv(socket) //ready last of data waiting on the port

//note this is the same port and address as the connection above
socket = socket(AF_INET, SOCK_STREAM, ptrp->p_proto);
ioctl(socket, FIONBIO, (char *)&on);
connect(socket)
send(socket,data)
shutdown(socket, SHUT_WR);
recv(socket) //read last of data waiting on the port

The other end of the connection takes approximately half a second to process all of this information, but my application finishes immediately.

The problem is that some of the data at the end of the first send is truncated though all of the data from the second send statement makes it to the other end, but if I add a 1 second sleep to the end of my application all of the data makes it successfully.

Why is this happening?
Brandon

You are enabling non-blocking IO on the socket with ioctl(), meaning, the program won't necessarily wait for it to finish(i.e. block). If you want it to wait for it, don't do that.

I modified my code to use poll to wait for data from sockets and commented out the ioctl() call and added poll() calls so that I wouldn't have to worry about waiting indefinitely on readable data to show up on the port which appears to have fixed my problem!

Thank you,
Brandon

---------- Post updated at 04:15 PM ---------- Previous update was at 02:12 PM ----------

Removing ioctl didn't fix the problem, the data just makes it to the port randomly now..
I see something on Wikipedia under TCP about close() on a port with data still in the queue, but it doesn't have a reference to how to fix the issue (I would post a link, but I haven't posted 5 articles yet!)

Are you actually closing the socket before the program ends?