You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取所有运行中Apache httpd进程的主目录(兼容Linux与Solaris)

问题

现有运行中的httpd进程快照如下:

$ ps -ef | grep '[b]in/httpd'
 wsadmin  8465  8463   0   Jul 13 ?           1:21 /web/apps/perf/apache/2.4.52/https-model/bin/httpd -k start
 wsadmin 23234 18662   0 14:00:34 ?           0:01 /web/apps/perf/apache/2.4.52/https-perf/bin/httpd -k start
 wsadmin 14098  6780   0   Jul 20 ?           1:07 /web/apps/perf/apache/2.4.52/https-msp/bin/httpd -k start
 wsadmin 28824 18662   0 11:31:13 ?           0:03 /web/apps/perf/apache/2.4.52/https-perf.web/bin/httpd -k start
 wsadmin  7380 18662   0 09:30:35 ?           0:03 /web/apps/perf/apache/2.4.52/https-perf.myapp/bin/httpd -k start

需要提取每个httpd进程的主目录(例如/web/apps/perf/apache/2.4.52/https-perf.myapp)。尝试过ps -ef | grep '[b]in/httpd' | awk '{print $8}',但由于主目录所在列不固定,该命令无法生效。

要求提供同时兼容Linux和Solaris的解决方案,其中Solaris版本信息如下:

uname -a SunOS myremsolhost 5.11 11.4.70.170.1 sun4v sparc sun4v non-global-zone

注意:Solaris中不支持grep -Po选项。

解决方案

可以通过awk动态定位httpd执行路径的列,再截取主目录,命令如下:

ps -ef | grep '[b]in/httpd' | awk '{for(i=1;i<=NF;i++){if($i ~ /\/bin\/httpd$/){sub(/\/bin\/httpd$/,"",$i); print $i}}}'

命令拆解

  • ps -ef | grep '[b]in/httpd':筛选出所有运行中的httpd进程([b]的写法可以避免匹配grep自身进程)
  • awk处理逻辑:
    • 遍历输出的每一列:for(i=1;i<=NF;i++)
    • 定位到以/bin/httpd结尾的列(即httpd的完整执行路径):if($i ~ /\/bin\/httpd$/)
    • 移除路径末尾的/bin/httpd:sub(/\/bin\/httpd$/,"",$i)
    • 打印处理后的主目录:print $i

该方法不依赖固定列数,同时兼容Linux和Solaris的awk实现,无需使用Solaris不支持的grep扩展选项。

内容的提问来源于stack exchange,提问作者Ashar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 16:57:37