【发布时间】:2011-09-28 20:29:10
【问题描述】:
我编写了一个程序来监视连接到 Linux 上的 RAID 的一些硬盘驱动器的状态。通过这个程序,我执行了几个命令行命令。但是发生了一个有趣的错误……程序运行了整整三分钟,然后它似乎无法再正确地执行之前执行的命令(对于多次迭代)。
它吐出一个数组索引错误(我的变量 driveLetters[d]),因为它似乎以某种方式错过了驱动器(即使它之前找到了数百次)。
其他需要注意的事项...如果我告诉它在超过驱动器数量时将 int "d" 重置为 "0"...程序不会崩溃,而是会陷入无限循环. 此外,程序崩溃的时间也各不相同。经过一定数量的间隔后,它似乎不会崩溃。最后,我没有收到任何类型的内存泄漏错误。
下面是一些应该显示错误的代码:
public static void scsi_generic() throws IOException, InterruptedException
{
int i =0;
int d =0;
int numberOfDrives = 8;
char driveLetters[] = {'b','c','d','e','f','g','h','i','j','k','l','m'};
String drive = "";
while (i <= numberOfDrives)
{
System.out.println("position 1");
List<String> commands = new ArrayList<String>();
commands.add("cat");
commands.add("/sys/class/scsi_generic/sg"+i+"/device/sas_address");
SystemCommandExecutor commandExecutor = new SystemCommandExecutor(commands);
int driveFound = commandExecutor.executeCommand();
if (driveFound == 0)
{
System.out.println("Folder: sg" + i + " was found." );
StringBuilder stdout = commandExecutor.getStandardOutputFromCommand();
String data = stdout.toString();
String sas = data.substring(11,12);
int sasA = Integer.parseInt(sas,16);
boolean matchedSG = false;
while (matchedSG == false)
{
System.out.println("position2");
List<String> lookSD = new ArrayList<String>();
lookSD.add("test");
lookSD.add("-d");
lookSD.add("/sys/class/scsi_generic/sg"+i+"/device/block:sd" + driveLetters[d]);
SystemCommandExecutor commandSearch = new SystemCommandExecutor(lookSD);
int sdFound = commandSearch.executeCommand();
StringBuilder stdout3 = commandSearch.getStandardOutputFromCommand();
StringBuilder stderr = commandSearch.getStandardErrorFromCommand();
String sdFound2 = stdout3.toString();
if (sdFound == 0)
{
matchedSG = true;
System.out.println("Found the SD drive.");
drive = "sd"+driveLetters[d];
System.out.println(sasA);
hdsas.set(sasA , sas);
d = 0;
i++;
loadDrives(drive , sasA);
}
/* else if (sdFound != )
{
System.out.println("Error:" + sdFound);
System.out.println(d+ " "+ i);
}
*/
else if ( d >= 8)
{
System.out.println("Drive letter: " + driveLetters[d]);
System.out.println("Int: " + i);
// System.out.println(sdFound2);
System.out.println("sd error: "+ sdFound);
// System.out.println(stderr);
//System.out.println(sdFound2 + " m");
}
else
{
d++;
}
}
}
else
{
System.out.println("Folder: sg" + i + " could not be found.");
i++;
}
d =0;
}
}
任何帮助或建议都会很棒!谢谢。
编辑:
我找到的解决方案是使用 java 库来测试目录是否存在,而不是通过 linux 命令行进行。
例如:
File location = new File("directory");
if (location.exists())
{
}
不知道为什么它可以工作并且不会崩溃,就像 linux 命令行在短时间内一样,但确实如此。
【问题讨论】:
-
请清理您发布的代码的缩进以使其可读。
-
遇到异常时是否打印了
d? -
是的,打印了 d。在数组越界异常之前,它总是以数组可能的最大数结束。
-
将我的解决方案添加到我的帖子中,简单修复。不知道为什么它会起作用。
标签: java linux command-line