A: 

You can use select() to determine if the socket is still available for writing. I've minimally modified your myconnect() function below (not exactly stellar flow control):

...

  sin.sin_family = AF_INET;

  if (connect(fd,(struct sockaddr *) &sin,sizeof(sin)) == -1) {
    log_error("connect:%d:%s", errno, strerror(errno));
    return 0;
  }

  FD_ZERO(&wfds);
  FD_SET(fd,&wfds);

  tv.tv_sec=0;
  tv.tv_usec=0;

  int retval;

  retval=select(fd+1, NULL, &wfds, NULL, &tv);
  if (!retval) {
    log_error("socket closed.");
  } else {
    nwritten = write(fd, &ch, 1);
    if (nwritten==-1) {
      log_error("write:%d:%s", errno, strerror(errno));
    } else {
      fprintf(stderr, "client : 1. written %ld\n", nwritten);
    }
  }
    sleep(3);

  retval=select(fd, NULL, &wfds, NULL, &tv);
  if (!retval) {
    log_error("socket closed.");
  } else {
    nwritten = write(fd, &ch, 1);
    if (nwritten==-1) {
      log_error("write:%d:%s", errno, strerror(errno));
    } else {
      fprintf(stderr, "client : 2. written %ld\n", nwritten);
    }
  }
    sleep(3);


  retval=select(fd, NULL, &wfds, NULL, &tv);
  if (!retval) {
    log_error("socket closed.");
  } else {
    nwritten = write(fd, &ch, 1);
    if (nwritten==-1) {
      log_error("write:%d:%s", errno, strerror(errno));
    } else {
      fprintf(stderr, "client : 3. written %ld\n", nwritten);
    }
  }
  return 0;
Crwth
This doesn't work, the behavior is the same as my original test program, the second select/write still succeeded.
Phuah Yee Keat
+3  A: 

You cannot rely just on the return value of write(2) - this is a big race condition between two ends of the connection (kernel caches the data you give to system calls, packets take time to cross the wire, etc.) and thus introduces a possibility of data loss in case of the transport-level connection tear-down. If you need reliability, design your application-level protocol so that receiving side acknowledges all data.

There used to be a nice article about something like this - The ultimate SO_LINGER page or why is my TCP not reliable, but it seems to be down at the moment. Google that title, it might be mirrored somewhere.

Nikolai N Fetissov
After 30 minutes of searching for the cache of the page, finally found it at http://ds9a.nl/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable.txt, this is the best I got, hope its the same as the original version.
Phuah Yee Keat