CGI 缓冲问题
我有一个基于 C 的服务器端 CGI 代码:
cgiFormFileSize("UPDATEFILE", &size); //UPDATEFILE = file being uploaded
cgiFormFileName("UPDATEFILE", file_name, 1024);
cgiFormFileContentType("UPDATEFILE", mime_type, 1024);
buffer = malloc(sizeof(char) * size);
if (cgiFormFileOpen("UPDATEFILE", &file) != cgiFormSuccess) {
exit(1);
}
output = fopen("/tmp/cgi.tar.gz", "w+");
inc = size/(1024*100);
fptr = fopen("progress_bar.txt", "w+");
while (cgiFormFileRead(file, b, sizeof(b), &got_count) == cgiFormSuccess)
{
fwrite(b,sizeof(char),got_count,output);
i++;
if(i == inc && j<=100)
{
fprintf(fptr,"%d", j);
fflush(fptr);
i = 0;
j++; // j is the progress bar increment value
}
}
fclose(fptr);
cgiFormFileClose(file);
retval = system("mkdir /tmp/update-tmp;\
cd /tmp/update-tmp;\
tar -xzf ../cgi.tar.gz;\
bash -c /tmp/update-tmp/update.sh");
但是,这并不像上面看到的那样工作。它不是将 1,2,...100 打印到progress_bar.txt(由 fptr 引用),而是一次性打印,似乎是缓冲然后写入文件。 fflush() 也不起作用。
任何线索/建议将不胜感激。
I have a server side C based CGI code as:
cgiFormFileSize("UPDATEFILE", &size); //UPDATEFILE = file being uploaded
cgiFormFileName("UPDATEFILE", file_name, 1024);
cgiFormFileContentType("UPDATEFILE", mime_type, 1024);
buffer = malloc(sizeof(char) * size);
if (cgiFormFileOpen("UPDATEFILE", &file) != cgiFormSuccess) {
exit(1);
}
output = fopen("/tmp/cgi.tar.gz", "w+");
inc = size/(1024*100);
fptr = fopen("progress_bar.txt", "w+");
while (cgiFormFileRead(file, b, sizeof(b), &got_count) == cgiFormSuccess)
{
fwrite(b,sizeof(char),got_count,output);
i++;
if(i == inc && j<=100)
{
fprintf(fptr,"%d", j);
fflush(fptr);
i = 0;
j++; // j is the progress bar increment value
}
}
fclose(fptr);
cgiFormFileClose(file);
retval = system("mkdir /tmp/update-tmp;\
cd /tmp/update-tmp;\
tar -xzf ../cgi.tar.gz;\
bash -c /tmp/update-tmp/update.sh");
However, this doesn't work the way as is seen above. Instead of printing 1,2,...100 to progress_bar.txt (referred by fptr)one by one it prints at ONE GO, seems it buffers and then writes to the file.
fflush() also didn't work.
Any clue/suggestion would be really appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它将其逐一写入,只是它执行得如此之快,以至于您几乎不可能看到其中包含除 99 之外的值的文件。
如果您在循环中放置
sleep(1)
,这样它的速度就足够慢,您可以捕获它,这一点很容易得到证明。It is writing it one-by-one, it's just that it does it so fast that you're vanishingly unlikely to ever see the file with a value other than 99 in it.
This is easily demonstrated if you put a
sleep(1)
within the loop, so that it's slow enough for you to catch it.首先,在循环之前打开文件,并在循环结束后关闭文件。 IO 太多。
问题出在这里
w+
- 这会截断您的文件。使用a+
。 (fopen 帮助)First, open the file before the loop and close after it ends. Too much IO.
The problem is here
w+
- this truncates your file. usea+
. (fopen help)