Win32调度程序并将stdout重定向到文件缓冲区问题?
在 Wi32 上 我正在尝试启动一个重定向到文件名(当前日期)的可执行文件,例如与:
Someexecutable.exe > 20101220000000.txt
当我从 Windows cmd.exe 执行此操作时,一切正常。然而,当从我的程序中执行此操作时,如下所示,系统似乎不会放弃重定向,即使它创建了文件和/或它似乎在刷新到磁盘之前缓冲了大量数据。 我无法更改正在运行的可执行文件。 现在执行的程序只写入标准输出,但请记住我根本无法更改它。 (最简单的方法是只执行 stdout = filehandle; 但遗憾的是,这对我来说现在是不可能的!)
(不需要:程序也等待 system() 这不是必需的,但是分离文件的最简单方法是什么?程序通过 system() 运行)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
char execstr[512];
char s[30];
size_t i;
struct tm tim;
time_t now;
now = time(NULL);
tim = *(localtime(&now));
i = strftime(s,30,"%Y%m%d%H%M",&tim);
sprintf(execstr,"someexecutable.exe > %s.txt",s);
printf("Executing: \"%s\"\n",execstr);
system(execstr);
exit(0);
return 0;
}
On Wi32
I am trying to start a executable who redirects to a filename (current date) e.g. the same as:
Someexecutable.exe > 20101220000000.txt
When I do this from windows cmd.exe everything works fine. However when doing this from my program as shown below the system seems ot either drop the redirect even if it creates the file and/or it seems to buffer a large amount of data before flushing to disk.
I can't change the executable that is being run.
The program beeing executed now only writes to stdout, but remember I can't change this at all. (the simplest way woud be to just do stdout = filehandle; but I that is sadly impossible for me right now!)
(Not required: Also the program waits as system() this is not required but what is the simplest way of detaching the program being run via system() )
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
char execstr[512];
char s[30];
size_t i;
struct tm tim;
time_t now;
now = time(NULL);
tim = *(localtime(&now));
i = strftime(s,30,"%Y%m%d%H%M",&tim);
sprintf(execstr,"someexecutable.exe > %s.txt",s);
printf("Executing: \"%s\"\n",execstr);
system(execstr);
exit(0);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为有任何原因无法正常工作,但如果您遇到这种情况,替代解决方案之一可能是使用 popen,然后从管道中读取数据以写入所需的文件。这是一些打印在屏幕上的示例代码。您可以根据您的要求将其写入文件而不是屏幕/控制台。
I don't see any reason for this to not work, but if this is the case with you, one of the alternative solution could be to use popen and then read from the pipe for writing in the desired file. Here is some sample code which is printing on the screen. You can write that to file instead of screen/console as per your requirement.
你的程序对我来说工作得很好(在 VS 2010 中测试)。如果您在 IDE 中运行测试,您可能会遇到的一些问题是:
someexecutable.exe
如果您更改程序以便使用
sprintf 的行()
调用看起来像:您在控制台窗口中看到
someexecutable.exe
的输出吗?Your program works fine for me (testing in VS 2010). Some problems you might run into if you're running your tests in the IDE are:
someexecutable.exe
If you change you program so that the line with the
sprintf()
call looks like:Do you see the output of
someexecutable.exe
in the console window?