#!/bin/bash

# 获取进程信息并按内存占用大小排序
processes=$(ps -eo pid,comm,rss,command --sort=-rss | awk '{if(NR>1) print $0}')

# 打印表头
printf "%-10s %-20s %-17s %-30s %-s\n" "PID" "程序名称" "内存占用（G）" "程序运行目录" "程序运行路径"

# 遍历进程信息并打印
while read -r line; do
    pid=$(echo "$line" | awk '{print $1}')
    program_name=$(echo "$line" | awk '{print $2}')
    memory_usage=$(echo "$line" | awk '{print $3}')
    program_path=$(echo "$line" | awk '{$1=$2=$3=""; print $0}')

    # 将内存占用由KB转换为GB
    memory_usage_gb=$(awk "BEGIN {printf \"%.2f\", $memory_usage/1024/1024}")

    # 获取程序运行目录
    program_cwd=$(readlink -e /proc/"$pid"/cwd)

    printf "%-10s %-20s %-17s %-30s %-s\n" "$pid" "$program_name" "$memory_usage_gb" "$program_cwd" "$program_path"
done <<< "$processes"