首页 > 解决方案 > 在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循环呢?

标签: cfwritefread

解决方案


(需要对评论进行格式化,所以临时 CW 回答)

只有当我强制停止服务器程序时,才会到达该打印行,然后程序退出。

(他按下 ^Z 把它推到背景中。)

问题不在发布的代码中。演示:在 之后添加以下行printf

fflush(stdout);
_exit(0);

噗,进程退出。


推荐阅读