技术解析
开了一个子进程来发送文件,发送完毕之后就 close 了 client_data_socket (数据 socket )
// 非阻塞
set_flag(client_data_socket, O_NONBLOCK);
pid_t pid;
if ((pid = fork()) < 0) {
printf("fork error");
continue;
} else if (pid == 0) {
FILE *fp;
if ((fp = fopen(filename, "rb")) == NULL)
{
close(client_data_socket);
printf("open file failed\n");
exit(1);
}
size_t char_size = sizeof(char);
char data_buffer[FILE_READ_BUFFER_SIZE];
int numread;
for (;;)
{
bzero(data_buffer, FILE_READ_BUFFER_SIZE);
numread = fread(data_buffer, char_size, FILE_READ_BUFFER_SIZE, fp);
if (numread < 0)
{
printf("read file failed\n");
break;
}
else if (numread > 0)
{
int length = send(client_data_socket, data_buffer, numread, 0);
if (length == 0)
{
break;
}
else if (length < 0)
{
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
{
continue;
}
printf("[PUT] command send data failed\n");
exit(1);
}
}
if (numread == FILE_READ_BUFFER_SIZE) continue;
else {
break;
}
}
close(client_data_socket);
fclose(fp);
exit(0);
} else {
int status = 0;
waitpid(pid, &status, 0);
if (status == 0)
printf("send file %s complete.\n", filename);
else
printf("send file %s failed.\n", filename);
}
然后,发送别的命令在 recv 的时候,命令端 socket 就阻塞了
Github