用C写入文件后,while循环不会退出 [英] While loop doesn't exit after writing to file in C
问题描述
我正在从客户端向服务器发送文件.我从客户端获取输入,在这种情况下,它用于文件传输,完成后客户端应该重新提示输入新命令.这是我发送文件的方式:
I'm sending a file from the client to the server. I take an input from the client, and in this case its for file transfer and after completion the client is supposed to reprompt for a new command. This is how I send a file:
客户端(发送):
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);
我遇到的问题是,打印语句printf("The server has received the requested document.\n");
从未执行过,这是我在执行所有操作的IF语句关闭之前打印的最后一条语句.而且我无法从客户端输入新命令,因为我认为它陷入了while循环中.仅当我强制停止服务器程序时,才达到该打印行,然后程序退出.奇怪的是,在我强制停止它之后,我可以看到传输的文件实际上已经正确传输了.但是为什么不离开while循环呢?
The problem I'm having, is that the print statement printf("The server has received the requested document.\n");
is never executed which is the last statement I print before this IF statement carrying all the operations is closed. And I'm unable to enter new commands from the client because I assume its stuck in this while loop. Only when I force stop the server program, that print line is reached and then the program exits. The strange thing, is that after I force stop it I can see that the file I transferred has actually been transferred correctly. But why wont it leave this while loop?
推荐答案
(需要在注释上设置格式,所以是临时的CW答案)
(need formatting on a comment, so temporary CW answer)
仅当我强制停止服务器程序时,到达该打印行,然后程序退出.
Only when I force stop the server program, that print line is reached and then the program exits.
(他按^ Z将其推到背景中.)
(He presses ^Z shoving it into the background.)
问题不在发布的代码中.演示:在printf
之后添加以下行:
The problem isn't in the posted code. Demonstration: add the following lines after printf
:
fflush(stdout);
_exit(0);
Po,进程退出.
这篇关于用C写入文件后,while循环不会退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!