c - 在C中写入文件后,循环不会退出
问题描述
我正在将文件从客户端发送到服务器。我从客户端获取输入,在这种情况下用于文件传输,完成后客户端应该重新提示输入新命令。这就是我发送文件的方式:
客户(发送):
size_t bytes_read = 0;
ssize_t bytes_written = 0;
while((bytes_read = fread(buf, 1, sizeof(buf), fp)) > 0){
if ((bytes_written = write(sd, buf, bytes_read)) < 0){
printf("Error sending client file.\n");
}
}
printf("bytes written: %ld\n", bytes_written);
fclose(fp);
}
服务器(接收):
while((bytes_read = read(sd, buf, sizeof(buf))) > 0){
printf("The contents: %s", buf);
fwrite(buf, 1, bytes_read, fp);
printf("Done writing\n");
}
printf("The server has received the requested document.\n");
fclose(fp);
我遇到的问题是 print 语句printf("The server has received the requested document.\n");
永远不会执行,这是我在执行所有操作的 IF 语句关闭之前打印的最后一条语句。而且我无法从客户端输入新命令,因为我认为它卡在这个 while 循环中。只有当我强制停止服务器程序时,才会到达该打印行,然后程序退出。奇怪的是,在我强制停止它之后,我可以看到我传输的文件实际上已经正确传输了。但是为什么它不会离开这个while循环呢?
解决方案
(需要对评论进行格式化,所以临时 CW 回答)
只有当我强制停止服务器程序时,才会到达该打印行,然后程序退出。
(他按下 ^Z 把它推到背景中。)
问题不在发布的代码中。演示:在 之后添加以下行printf
:
fflush(stdout);
_exit(0);
噗,进程退出。
推荐阅读
- powershell - Get-ADComputer 仅打印部分名称
- django - 有效地从我的模型中列出第 3 级数据的问题(Django)
- javascript - 如何将对象推入数组角度 8
- python-3.x - 来自数据框的带有子图的多个图形
- python - 将列表的第一个和最后一个元素相加
- bash - 脚本退出时后台作业不干净
- email - 对 Google 表格中的特定数据进行更改时的电子邮件通知
- elasticsearch - Elasticsearch Painless script 的问题
- material-table - 在反应js中从外部材料表单击按钮时在材料表中添加行
- python - 在 Python 中失败时重新连接到 Websocket