read
对/的每次调用write
都应进行测试,并应在出错时重新建立连接:
在文件main.c
中,而不是
//set up the connection
socket_id = get_socket();
get_ip_address("example.com");
establish_connection(socket_id);
/*...*/
//send the request
while(1) {
if(write(socket_id, request, strlen(request)) == -1 || read(socket_id, message, 1024 * 1024) == -1) {
establish_connection(socket_id);
write(socket_id, request, strlen(request));
read(socket_id, message, 1024 * 1024);
}else {
write(socket_id, request, strlen(request));
read(socket_id, message, 1024 * 1024);
}
}
你应该写这样的东西:
/* query should be declared before this point */
while (1)
{
/* set up the connection */
socket_id = get_socket();
get_ip_address("example.com");
establish_connection(socket_id);
/* send the request */
while (1)
{
if (write(socket_id, request, strlen(request))<=0)
{
/* something goes wrong while writing, exit the inner while loop */
perror("write");
break;
}
if (read(socket_id, message, 1024 * 1024)<=0)
{
/* something goes wrong while reading, exit the inner while loop */
perror("read");
break;
}
}
/* if this point is reach, that means that one write or read call goes wrong */
close(socket_id);
}