[英].NET Core on Linux: Is stdout redirected?
在 Windows 上,我使用此代碼來確定是否為當前正在運行的進程重定向了 stdout 流:
private static bool? isOutputRedirected;
public static bool IsOutputRedirected
{
get
{
if (isOutputRedirected == null)
{
isOutputRedirected =
GetFileType(GetStdHandle(StdHandle.Output)) != FileType.FileTypeChar ||
!GetConsoleMode(GetStdHandle(StdHandle.Output), out _);
// Additional GetConsoleMode check required to detect redirection to "nul"
}
return isOutputRedirected == true;
}
}
private enum StdHandle : int
{
Input = -10,
Output = -11,
Error = -12,
}
private enum FileType : uint
{
FileTypeChar = 0x0002,
FileTypeDisk = 0x0001,
FileTypePipe = 0x0003,
FileTypeRemote = 0x8000,
FileTypeUnknown = 0x0000,
}
[DllImport("kernel32.dll")]
private static extern FileType GetFileType(IntPtr hFile);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(StdHandle nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
對於其他兩個標准流,我有類似的屬性。
這是在顯示進度信息或嘗試用新內容更新當前行時處理情況所必需的。 這在輸出被重定向時沒有用,因此輸出應該減少為更簡單的內容。
但這在 Linux 上運行時會按預期失敗( dotnet publish -r linux-arm
)。
如何在 Linux 上確定相同的情況? 網絡似乎對此一無所知(還)。
對於 .NET Framework 4.5 及更高版本,您可能需要查看Console.IsOutputRedirected
和Console.IsErrorRedirected
來源: https : //docs.microsoft.com/en-us/dotnet/api/system.console?view=netcore-3.1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.