问题描述
当我使用 popen 获取命令的输出时,比如 dir,它会提示一个控制台.
when I use popen to get the output of a command, say dir, it will prompt out a console.
但是,我可以在没有控制台出现的情况下获得命令的输出吗?
however, can I get the output of a command without the appearance of the console?
我正在使用 Visual C++,并希望创建一个库来返回某些命令的输出,例如 dir.
I am using Visual C++ and want to make an Library to return the output of some command, say, dir.
推荐答案
假设 Windows(因为这是唯一普遍存在这种行为的平台):
Assuming Windows (since this is the only platform where this behavior is endemic):
CreatePipe() 来创建通信所需的管道,以及 CreateProcess创建子进程.
CreatePipe() to create the pipes necessary to communicate, and CreateProcess to create the child process.
HANDLE StdInHandles[2];
HANDLE StdOutHandles[2];
HANDLE StdErrHandles[2];
CreatePipe(&StdInHandles[0], &StdInHandles[1], NULL, 4096);
CreatePipe(&StdOutHandles[0], &StdOutHandles[1], NULL, 4096);
CreatePipe(&StdErrHandles[0], &StdErrHandles[1], NULL, 4096);
STARTUPINFO si; memset(&si, 0, sizeof(si)); /* zero out */
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = StdInHandles[0]; /* read handle */
si.hStdOutput = StdOutHandles[1]; /* write handle */
si.hStdError = StdErrHandles[1]; /* write handle */
/* fix other stuff in si */
PROCESS_INFORMATION pi;
/* fix stuff in pi */
CreateProcess(AppName, commandline, SECURITY_ATTRIBUTES, SECURITY_ATTRIBUTES, FALSE, CREATE_NO_WINDOW |DETACHED_PROCESS, lpEnvironment, lpCurrentDirectory, &si, &pi);
这不仅仅是让你走上你希望完成的道路.
This should more than get you on your way to doing what you wish to accomplish.
这篇关于没有控制台的 C++ popen 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!