我正在编写一个应用程序,它将一些诊断信息转储到标准输出.
I'm writing an application which dumps some diagnostics to the standard output.
我想让应用程序以这种方式工作:
I'd like to have the application work this way:
cmd.exe
)运行或将标准输出重定向/管道到文件,则在完成后立即退出,cmd.exe
) or has standard output redirected/piped to a file, exit cleanly as soon as it finished,我该如何区分?我怀疑检查父进程可能是一种方法,但我并不是真的很喜欢 WinAPI,因此这个问题.
我在 MinGW GCC 上.
I'm on MinGW GCC.
您可以使用 GetConsoleWindow,GetWindowThreadProcessId 和 GetCurrentProcessId 方法.
You can use GetConsoleWindow, GetWindowThreadProcessId and GetCurrentProcessId methods.
1) 首先,您必须使用 GetConsoleWindow
函数检索控制台窗口的当前句柄.
1) First you must retrieve the current handle of the console window using the GetConsoleWindow
function.
2) 然后你会得到控制台窗口句柄的进程所有者.
2) Then you get the process owner of the handle of the console window.
3) 最后,将返回的 PID 与应用程序的 PID 进行比较.
3) Finally you compare the returned PID against the PID of your application.
检查此示例(VS C++)
Check this sample (VS C++)
#include "stdafx.h"
#include <iostream>
using namespace std;
#if _WIN32_WINNT < 0x0500
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#include <windows.h>
#include "Wincon.h"
int _tmain(int argc, _TCHAR* argv[])
{
HWND consoleWnd = GetConsoleWindow();
DWORD dwProcessId;
GetWindowThreadProcessId(consoleWnd, &dwProcessId);
if (GetCurrentProcessId()==dwProcessId)
{
cout << "I have my own console, press enter to exit" << endl;
cin.get();
}
else
{
cout << "This Console is not mine, good bye" << endl;
}
return 0;
}
这篇关于如何检查程序是否从控制台运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!