确定 Java 程序是否已从交互式 shell 启动

2022-09-04 04:44:51

我曾经认为

System.console() != null

是确定启动我的 Java 应用程序的 shell 是否具有交互性的可靠方法。这允许我在交互模式下使用ANSI转义序列,并且每当程序的输出被重定向到文件或通过管道传输到其他进程的stdin时,就像许多GNU实用程序的--color=auto模式一样。System.outSystem.err

System.console()但是,Windows 中的行为是不同的。虽然当JVM启动时,该方法确实返回了一个非值(这对我来说是无用的,因为不理解转义序列),但返回值总是当我从Cygwin-- ,中可用的任何终端仿真器启动我的程序时(最后一个只是一个正在运行的子进程)。nullcmd.execmd.exenullxtermminttycygwincmd.exebash

如何在Java中测试交互式shell,而无需在shell脚本中读取并将命令行参数传递给我的Java程序?从 Java 测试环境变量不是一个选项,因为 Java 是从 shell 脚本启动的,因此父进程是非交互式 shell,并且未设置。$-PS1PS1


答案 1

在一个对话中,Cygwin的维护者(Corinna Vinschen)解释说,Cygwin伪TTY看起来像是Microsoft Visual C运行时库(MSVCRT)的管道。她还建议围绕识别Cygwin伪TTY的函数实现一个包装器。isatty()

这个想法是获取与给定文件描述符关联的管道的名称。NtQueryInformationFile 函数提取FILE_NAME_INFORMATION结构,其中成员包含管道名称。如果管道名称与以下模式匹配,则该命令很可能在交互模式下运行:FileName

\cygwin-%16llx-pty%d-{to,from}-master

对话已经很老了,但管道名称的格式仍然相同:“\\\\.\\pipe\\cygwin-” + “%S-” + “pty%d-from-master”,其中是命名管道的召集前缀(请参阅 CreateNamedPipe)。"\\\\.\\pipe\\"

因此,Cygwin部分已经被黑客入侵。下一步是从C代码创建Java函数。

下面使用通过 Java 本机接口 (JNI) 实现的方法创建类。该代码在GNU/Linux()和Cygwin Windows 7(64位)上进行了测试。代码可以很容易地移植到Windows(),甚至可以按原样工作。ttyjni.TestAppistty()x86_64cmd.exe

所需组件

  • Cygwin with compilerx86_64-w64-mingw32-gcc
  • 带有 JDK 的 Windows

布局

├── Makefile
├── TestApp.c
├── test.sh
├── ttyjni
│   └── TestApp.java
└── ttyjni_TestApp.h

制作文件

# Input: $JAVA_HOME

FINAL_TARGETS := TestApp.class

ifeq ($(OS),Windows_NT)
  CC=x86_64-w64-mingw32-gcc
  FINAL_TARGETS += testapp.dll
else
  CC=gcc
  FINAL_TARGETS += libtestapp.so
endif

all: $(FINAL_TARGETS)

TestApp.class: ttyjni/TestApp.java
  javac $<

testapp.dll: TestApp.c TestApp.class
  $(CC) \
    -Wl,--add-stdcall-alias \
    -D__int64="long long" \
    -D_isatty=isatty -D_fileno=fileno \
    -I"$(JAVA_HOME)/include" \
    -I"$(JAVA_HOME)/include/win32" \
    -shared -o $@ $<

libtestapp.so: TestApp.c
  $(CC) \
    -I"$(JAVA_HOME)/include" \
    -I"$(JAVA_HOME)/include/linux" \
    -fPIC \
    -o $@ -shared -Wl,-soname,testapp.so $<  \
    -z noexecstack

clean:
  rm -f *.o $(FINAL_TARGETS) ttyjni/*.class

TestApp.c

#include <jni.h>
#include <stdio.h>
#include "ttyjni_TestApp.h"

#if defined __CYGWIN__ || defined __MINGW32__ || defined __MINGW64__
#include <io.h>
#include <errno.h>
#include <wchar.h>
#include <windows.h>
#include <winternl.h>
#include <unistd.h>


/* vvvvvvvvvv From http://cygwin.com/ml/cygwin/2012-11/txt00003.txt vvvvvvvv */

#ifndef __MINGW64_VERSION_MAJOR
/* MS winternl.h defines FILE_INFORMATION_CLASS, but with only a
   different single member. */
enum FILE_INFORMATION_CLASSX
{
  FileNameInformation = 9
};

typedef struct _FILE_NAME_INFORMATION
{
  ULONG FileNameLength;
  WCHAR FileName[1];
} FILE_NAME_INFORMATION, *PFILE_NAME_INFORMATION;

NTSTATUS (NTAPI *pNtQueryInformationFile) (HANDLE, PIO_STATUS_BLOCK, PVOID,
    ULONG, FILE_INFORMATION_CLASSX);
#else
NTSTATUS (NTAPI *pNtQueryInformationFile) (HANDLE, PIO_STATUS_BLOCK, PVOID,
    ULONG, FILE_INFORMATION_CLASS);
#endif

jint
testapp_isatty(jint fd)
{
  HANDLE fh;
  NTSTATUS status;
  IO_STATUS_BLOCK io;
  long buf[66]; /* NAME_MAX + 1 + sizeof ULONG */
  PFILE_NAME_INFORMATION pfni = (PFILE_NAME_INFORMATION) buf;
  PWCHAR cp;


  /* First check using _isatty.

     Note that this returns the wrong result for NUL, for instance!
     Workaround is not to use _isatty at all, but rather GetFileType
     plus object name checking. */
  if (_isatty(fd))
    return 1;

  /* Now fetch the underlying HANDLE. */
  fh = (HANDLE)_get_osfhandle(fd);
  if (!fh || fh == INVALID_HANDLE_VALUE) {
    errno = EBADF;
    return 0;
  }

  /* Must be a pipe. */
  if (GetFileType (fh) != FILE_TYPE_PIPE)
    goto no_tty;

  /* Calling the native NT function NtQueryInformationFile is required to
     support pre-Vista systems.  If that's of no concern, Vista introduced
     the GetFileInformationByHandleEx call with the FileNameInfo info class,
     which can be used instead. */
  if (!pNtQueryInformationFile) {
    pNtQueryInformationFile = (NTSTATUS (NTAPI *)(HANDLE, PIO_STATUS_BLOCK,
          PVOID, ULONG, FILE_INFORMATION_CLASS))
      GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQueryInformationFile");
    if (!pNtQueryInformationFile)
      goto no_tty;
  }
  if (!NT_SUCCESS (pNtQueryInformationFile (fh, &io, pfni, sizeof buf,
          FileNameInformation)))
    goto no_tty;

  /* The filename is not guaranteed to be NUL-terminated. */
  pfni->FileName[pfni->FileNameLength / sizeof (WCHAR)] = L'\0';

  /* Now check the name pattern.  The filename of a Cygwin pseudo tty pipe
     looks like this:

     \cygwin-%16llx-pty%d-{to,from}-master

     %16llx is the hash of the Cygwin installation, (to support multiple
     parallel installations), %d id the pseudo tty number, "to" or "from"
     differs the pipe direction. "from" is a stdin, "to" a stdout-like
     pipe. */
  cp = pfni->FileName;
  if (!wcsncmp(cp, L"\\cygwin-", 8)
      && !wcsncmp (cp + 24, L"-pty", 4))
  {
    cp = wcschr(cp + 28, '-');
    if (!cp)
      goto no_tty;
    if (!wcscmp (cp, L"-from-master") || !wcscmp (cp, L"-to-master"))
      return 1;
  }
no_tty:
  errno = EINVAL;
  return 0;
}

/* ^^^^^^^^^^ From http://cygwin.com/ml/cygwin/2012-11/txt00003.txt ^^^^^^^^ */

#elif _WIN32
#include <io.h>

static jint
testapp_isatty(jint fd)
{
  return _isatty(fd);
}
#elif defined __linux__ || defined __sun || defined __FreeBSD__
#include <unistd.h>

static jint
testapp_isatty(jint fd)
{
  return isatty(fd);
}
#else
#error Unsupported platform
#endif /* __CYGWIN__ */

JNIEXPORT jboolean JNICALL Java_ttyjni_TestApp_istty
(JNIEnv *env, jobject obj)
{
  return testapp_isatty(fileno(stdin)) &&
    testapp_isatty(fileno(stdout)) ?
    JNI_TRUE : JNI_FALSE;
}

ttyjni_TestApp.h

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class ttyjni_TestApp */

#ifndef _Included_ttyjni_TestApp
#define _Included_ttyjni_TestApp
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     ttyjni_TestApp
 * Method:    istty
 * Signature: ()Z
 */
JNIEXPORT jboolean JNICALL Java_ttyjni_TestApp_istty
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

ttyjni/TestApp.java

package ttyjni;

import java.io.Console;
import java.lang.reflect.Method;

class TestApp {
    static {
        System.loadLibrary("testapp");
    }
    private native boolean istty();

    private static final String ISTTY_METHOD = "istty";
    private static final String INTERACTIVE = "interactive";
    private static final String NON_INTERACTIVE = "non-interactive";

    protected static boolean isInteractive() {
        try {
            Method method = Console.class.getDeclaredMethod(ISTTY_METHOD);
            method.setAccessible(true);
            return (Boolean) method.invoke(Console.class);
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        return false;
    }

    public static void main(String[] args) {
        // Testing JNI
        TestApp t = new TestApp();
        boolean b = t.istty();
        System.out.format("%s(jni)\n", b ?
                "interactive" : "non-interactive");

        // Testing pure Java
        System.out.format("%s(console)\n", System.console() != null ?
                INTERACTIVE : NON_INTERACTIVE);
        System.out.format("%s(java)\n", isInteractive() ?
                INTERACTIVE : NON_INTERACTIVE);
    }
}

test.sh

#!/bin/bash -
java -Djava.library.path="$(dirname "$0")" ttyjni.TestApp

编译

make

在 Linux 上测试

$ ./test.sh
interactive(jni)
interactive(console)
interactive(java)

$ ./test.sh > 1
ruslan@pavilion ~/tmp/java $ cat 1
non-interactive(jni)
non-interactive(console)
non-interactive(java)

在天鹅座上进行测试

$ ./test.sh
interactive(jni)
non-interactive(console)
non-interactive(java)

$ ./test.sh > 1
$ cat 1
non-interactive(jni)
non-interactive(console)
non-interactive(java)

答案 2

推荐