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;