1

我正在编写一个具有多个线程的 Java 程序。其中一个线程负责从标准输入中读取行并对其进行解析。

正常运行时一切正常,但是当程序在后台(在 Linux 中)运行时,使用:

$ java -jar my_jar_file &

我的程序挂起(至少在被带到前台之前)。

在后台运行时,我真的不需要标准输入,但我也不希望我的程序挂起。

我搜索了一种以编程方式确定进程是否在后台运行但找不到的方法。

下面是从标准输入读取的代码:

InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inputStreamReader);

String line = null;

try {
  while ((line = br.readLine()) != null) {
    parseInputLine(line, br);
  }
} catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

据我所知,程序在到达br.readLine()命令时挂起。

4

4 回答 4

0

我猜读者正在阻止等待输入您可能能够从命令行输入您的输入

于 2013-08-22T15:07:56.393 回答
0

I don't believe a Java program can determine if it's running in foreground or background.

I tried System.console(), with the following results:

  • Linux - returns null if stdin is redirected from a file, independent of foreground/background status
  • Windows - same thing;
  • Cygwin - seems to always return null

I suspect you will need to invoke the program from the command line as

java -cp ... ClassName < /dev/null
于 2013-08-22T17:13:34.170 回答
0

readLine 是一个阻塞调用。所以它显然是在等待输入。如果您希望它在后台运行,则将来自这样的文件的输入传递给它

java TakeInput < test.txt &

这里的类如下,test.txt 也如下所示:

public class TakeInput
{
    public static void main(String[] args)
    {
        InputStreamReader inputStreamReader = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(inputStreamReader);

        String line = null;

        try {
          while ((line = br.readLine()) != null) {
              System.out.println(line);
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
    }
}

写一个文本文件作为 test.txt 说

test1
test2
test3
于 2013-08-22T15:45:21.543 回答
0

尝试使用 .ready() 函数。

try {
      if (stdError.ready()) 
      {
            while((line= stdError.readLine()) != null){
                logger.error(line);
            }
      }
}

对标准输出做同样的事情。

于 2016-06-09T08:29:10.853 回答