用java 获取ubuntu 系统中指定进程的资源占用情况,并保存mysql
时间: 2024-02-05 09:13:33 浏览: 156
要获取Ubuntu系统中指定进程的资源占用情况,可以使用Java中的ProcessBuilder类和Linux命令行工具top。具体步骤如下:
1. 使用ProcessBuilder类启动top命令,并将输出流重定向到Java程序中。
```java
ProcessBuilder pb = new ProcessBuilder("top", "-b", "-n", "1", "-p", "pid");
pb.redirectErrorStream(true);
Process process = pb.start();
```
其中,pid是指定进程的进程号。
2. 读取top命令的输出,解析出需要的资源占用情况。
```java
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(pid)) {
String[] tokens = line.trim().replaceAll("\\s+", " ").split(" ");
double cpuUsage = Double.parseDouble(tokens[8]);
double memUsage = Double.parseDouble(tokens[9]);
// do something with cpuUsage and memUsage
}
}
```
在解析top命令的输出时,我们只需要找到指定进程的行,然后提取出CPU使用率和内存使用率即可。
3. 将资源占用情况保存到MySQL数据库中。
```java
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
PreparedStatement stmt = conn.prepareStatement("INSERT INTO process_usage(pid, cpu_usage, mem_usage) VALUES (?, ?, ?)");
stmt.setInt(1, pid);
stmt.setDouble(2, cpuUsage);
stmt.setDouble(3, memUsage);
stmt.executeUpdate();
```
在保存资源占用情况时,我们可以将进程号、CPU使用率和内存使用率保存到MySQL数据库中的一个表中。需要注意的是,需要提前创建好表和相关的数据库连接。
阅读全文
相关推荐
















