用java 根据进程名称获取ubuntu 系统中指定进程的资源占用情况,并保存mysql
时间: 2024-02-05 12:13:47 浏览: 32
要获取Ubuntu系统中指定进程的资源占用情况,可以使用Java的ProcessBuilder类来启动并执行Linux命令,并通过解析命令输出的结果来获取所需信息。以下是一个示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ProcMonitor {
public static void main(String[] args) {
String procName = "process_name"; // 进程名称
String cmd = "ps aux | grep " + procName; // Linux命令
try {
ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", cmd);
Process process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
// 解析命令输出的每行信息,获取所需的资源占用情况
String[] fields = line.trim().split("\\s+");
String pid = fields[1]; // 进程ID
String cpuUsage = fields[2]; // CPU占用率
String memUsage = fields[3]; // 内存占用率
// 保存到MySQL数据库中
saveToDatabase(pid, cpuUsage, memUsage);
}
int exitCode = process.waitFor();
if (exitCode != 0) {
System.err.println("Command execution failed with exit code " + exitCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void saveToDatabase(String pid, String cpuUsage, String memUsage) throws SQLException {
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "mypassword";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO process_usage (pid, cpu_usage, mem_usage) VALUES (?, ?, ?)")) {
stmt.setString(1, pid);
stmt.setString(2, cpuUsage);
stmt.setString(3, memUsage);
stmt.executeUpdate();
}
}
}
```
在以上代码中,我们使用ProcessBuilder类启动Linux命令,并通过解析命令输出的结果获取进程ID、CPU占用率和内存占用率等信息。然后将这些信息保存到MySQL数据库中。注意,要保存到数据库中,需要先下载并安装MySQL JDBC驱动程序,并在代码中指定数据库连接信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)