How do I redirect output to a file with CreateProcess?(如何使用 CreateProcess 将输出重定向到文件?)
问题描述
我尝试使用 CreateProcess 来运行一个简单的命令,例如 hg >测试.txt.我尝试将字符串作为一个整体运行(而不是将其分成应用程序名称及其参数).为什么 CreateProcess(0, "notepad.exe test.txt", ...) 工作但 CreateProcess(0, "hg > test.txt", ...)代码> 没有?
I tried using CreateProcess to run a simple command like hg > test.txt. I tried running the string as a whole (as opposed to separating it into an application name and its parameters). Why does CreateProcess(0, "notepad.exe test.txt", ...) work but CreateProcess(0, "hg > test.txt", ...) does not?
推荐答案
不能在传递给 CreateProcess.要重定向标准输出,您需要在 STARTUPINFO 结构.
You can't use stdout redirection in the command line passed to CreateProcess. To redirect stdout you need to specify a file handle for the output in the STARTUPINFO structure.
您还犯了另一个更微妙的错误.第二个参数 lpCommandLine 必须指向可写内存,因为 CreateProcess 会覆盖缓冲区.如果您碰巧使用了该函数的 ANSI 版本,那么您可以避免使用该函数,但不适用于 Unicode 版本.
You are also making another, more subtle, mistake. The second parameter, lpCommandLine must point to writeable memory because CreateProcess overwrites the buffer. If you happen to be using the ANSI version of the function then you will get away with this, but not for the Unicode version.
这个函数的 Unicode 版本,CreateProcessW,可以修改这个字符串的内容.因此,该参数不能是指向只读内存的指针(例如const 变量或文字字符串).如果此参数是一个常量字符串,该函数可能会导致访问冲突.
The Unicode version of this function, CreateProcessW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation.
这篇关于如何使用 CreateProcess 将输出重定向到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 CreateProcess 将输出重定向到文件?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
