开了一个子进程来发送文件,发送完毕之后就 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
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.