0

我定义了一个函数来返回命令过程输出,在 Windows 中它工作正常,但在 Linux 中它失败了。

从命令ps -u root|grep java|awk '{print $1}'它总是返回null

甚至在执行此方法之前,我尝试在命令提示符下执行命令,它成功了

#ps -u root|grep java|awk '{print $1}'

385

2018

2048

4242

21290

25110

25589

26166

/**
 * This method will execute and returns the command output
 * @param commandToBeExecute
 * @return
 */
protected String getCMDOutput(final String commandToBeExecute)
{
    String cmdOutput = "";
    InputStream inputstream = null;
    InputStreamReader inputstreamreader = null;
    try 
    {
        final Process process = runTime.exec(commandToBeExecute);
        inputstream = process.getInputStream();
        inputstreamreader = new InputStreamReader(inputstream);
        bufferedReader = new BufferedReader(inputstreamreader);
        String currentLine;
        currentLine = bufferedReader.readLine();\\Always returning null for **ps -u root|grep java|awk '{print $1}'** command
        while(currentLine!=null)
        {
            cmdOutput += currentLine;
            currentLine = bufferedReader.readLine();
        }
    } 
    catch (IOException ioException) {
        logger.error(ioException.getMessage(), ioException);
    }
    finally
    {
        try
        {
            if(bufferedReader!=null)
            {
                bufferedReader.close();
            }
            if(inputstream!=null)
            {
                inputstream.close();
            }
            if(inputstreamreader!=null)
            {
                inputstreamreader.close();
            }           
        } 
        catch (IOException ioException) {
            logger.error(ioException.getMessage(), ioException);
        }
    }
    return cmdOutput;
}

当我尝试下面的代码时,它给出了一个错误

inputstream = process.getErrorStream();
        inputstreamreader = new InputStreamReader(inputstream);
        bufferedReader = new BufferedReader(inputstreamreader);
        currentLine = bufferedReader.readLine();

 (java.lang.String) ERROR: User name does not exist.

那么,这个错误的原因是什么,请指导解决以解决这个问题。

4

1 回答 1

0
currentLine = bufferedReader.readLine();\\Always returning null for **ps -u root|grep java|awk '{print $1}'** command
        while(currentLine!=null)
        {
            cmdOutput += currentLine;
            currentLine = bufferedReader.readLine();
        }

将上面的代码更改为:并尝试一次。

    while((currentLine = bufferedReader.readLine())!=null)
    {
        cmdOutput += currentLine;
        //currentLine = bufferedReader.readLine();
    }
于 2013-04-12T09:09:34.877 回答