콘솔에서 프로그램이 실행되는지 확인하는 방법은 무엇입니까?
진단서를 표준 출력에 덤핑하는 애플리케이션을 쓰고 있습니다.
애플리케이션을 다음과 같은 방식으로 작동시키고 싶습니다.
- 독립 실행형 명령 프롬프트에서 실행되는 경우(를 통해)
cmd.exe
) 또는 표준 출력을 파일로 리디렉션/파이프 처리하여 완료되는 즉시 깨끗하게 종료합니다. - 그렇지 않으면(창에서 실행되고 콘솔 창이 자동으로 생성되는 경우) 창이 사라지기 전에 종료하기 전에 키를 누를 때까지 기다립니다(사용자가 진단을 읽을 수 있도록)
어떻게 그 구별을 할 수 있을까요?부모 프로세스를 검토하는 것이 방법이 될 수 있다고 생각하지만 저는 WinAPI에 관심이 없어서 의문입니다.
저는 MinGW GCC입니다.
및 메서드를 사용할 수 있습니다.
먼저 콘솔 창의 현재 핸들을 사용하여 검색해야 합니다.
GetConsoleWindow
기능.그러면 콘솔 창의 핸들에 대한 프로세스 소유자를 얻게 됩니다.
마지막으로 반환된 PID를 응용 프로그램의 PID와 비교합니다.
이 샘플 확인(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;
}
일반적인 테스트는 다음과 같습니다.
if( isatty(STDOUT_FILENO)) {/* 이것은 터미널입니다 */}
C#에서 이걸 필요로 했어요.번역은 다음과 같습니다.
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcessId();
[DllImport("user32.dll")]
static extern int GetWindowThreadProcessId(IntPtr hWnd, ref IntPtr ProcessId);
static int Main(string[] args)
{
IntPtr hConsole = GetConsoleWindow();
IntPtr hProcessId = IntPtr.Zero;
GetWindowThreadProcessId(hConsole, ref hProcessId);
if (GetCurrentProcessId().Equals(hProcessId))
{
Console.WriteLine("I have my own console, press any key to exit");
Console.ReadKey();
}
else
Console.WriteLine("This console is not mine, good bye");
return 0;
}
Microsoft의 I18N 전문가 Michael Kaplan은 자신의 블로그에 콘솔의 리디렉션 여부를 포함하여 콘솔의 여러 가지 사항을 확인할 수 있는 일련의 방법을 제공했습니다.
C#로 작성되어 있지만, C나 C++로 포팅하는 것은 Win32 API에 대한 호출을 모두 수행하기 때문에 매우 간단할 것입니다.
여러 가지 API와 호출을 시도해 본 결과, 작동하는 방법은 단 한 가지에 불과했습니다.
// #include <io.h>
bool isConsole = isatty(fileno(stdin));
콘솔 응용 프로그램을 실행하고 출력을 다음을 사용하여 파일로 리디렉션할 수 있으므로 stdout을 사용할 수 없습니다.>log.txt
스위치를 바꾸다입력을 리디렉션하는 것도 가능하지만 콘솔 응용 프로그램을 실행할 때는 거의 사용되지 않는 기능인 것 같습니다.
언급URL : https://stackoverflow.com/questions/9009333/how-to-check-if-the-program-is-run-from-a-console
'sourcecode' 카테고리의 다른 글
심포니 CSRF and Ajax (0) | 2023.10.31 |
---|---|
how to toggle attr() in jquery (0) | 2023.10.31 |
mysql 쿼리에서 일련 번호 생성 (0) | 2023.10.26 |
Oracle to Excel - PL/SQL 내보내기 절차 (0) | 2023.10.26 |
Laravel이 이미 백엔드로 사용되고 있다면 프론트엔드에서 AngularJs를 사용하는 이유는 무엇입니까? (0) | 2023.10.26 |