实施“系统"Java中的命令

2022-01-18 00:00:00 process subprocess system javascript java

我需要一个系统"函数调用,与 Python、Perl、PHP、Ruby 和 &c 中的函数调用相同.当它在 Rhino JavaScript 引擎上运行时,它将成为一个名为 Narwhal 的 JavaScript 标准库的组件,而 Rhino JavaScript 引擎又在 Java 上运行.

I have need for a "system" function call, the same as those in Python, Perl, PHP, Ruby, &c. It will be a component of a JavaScript standard library called Narwhal, when it's run on the Rhino JavaScript engine, which is in turn run on Java.

问题在于,Java 的标准库似乎已经抽象出生成子进程的能力,该子进程共享父进程的标准输入输出.这意味着您不能将交互性推迟到子流程.

The trouble is that Java's standard library appears to have abstracted away the ability to spawn a subprocess that shares the parent process's stdio. This means that you can't defer interactivity to the subprocess.

我的第一次尝试是实现 Python 的 subprocess.popen.这使用三个泵"线程来主动独立地复制父进程的标准输入输出(以防止死锁).不幸的是,这给我们带来了两个问题.首先,当子进程自愿退出时,输入不会自动关闭.其次,子进程的流没有正确缓冲和刷新.

My first crack at this was to implement Python's subprocess.popen. This uses three "pumper" threads to actively copy the parent process's stdio independently (to prevent deadlock). Unfortunately this is giving us two problems. First, the input does not close automatically when the sub-process voluntarily exits. Second, the streams to the child process do not buffer and flush properly.

我正在寻找能够使我们的 require("os").system() 命令按预期工作的解决方案.

I'm looking for solutions that would make our require("os").system() command work as one would expect.

该项目位于 http://narwhaljs.org

相关代码:

  • http://github.com/tlrobinson/narwhal/blob/d147c160f11fdfb7f3c0763acf352b2b0e2713f7/lib/os.js#L10
  • http://github.com/tlrobinson/narwhal/blob/d147c160f11fdfb7f3c0763acf352b2b0e2713f7/engines/rhino/lib/os-engine.js#L37

推荐答案

不确定这是否是你要找的,但你可以通过 system 函数"https://github.com/twall/jna/" rel="nofollow noreferrer">JNA 库:

Not sure if this is what you're looking for, but you can invoke the C system function through the JNA library:

public class System {
  public interface C extends Library {
    C INSTANCE = (C) Native.loadLibrary(
        (Platform.isWindows() ? "msvcrt" : "c"), C.class);

    public int system(String format);
  }

  public static void main(String[] args) {
    C.INSTANCE.system("vi");
  }
}

无论如何,粗略测试在 Windows 上运行.

Cursory testing worked on Windows, anyhow.

相关文章