我想向我在Linux和Mac OS X上使用system
或system2
开始的流程发送信号。但是,通过他们的文档我无法找到任何方法来查找pid新开始的过程。
答案 0 :(得分:4)
答案 1 :(得分:1)
事实证明这并不像我想象的那么简单。我正在执行的命令启动了其他进程,我需要杀死的进程在进程树的下方。所以,即使系统/系统给了我们开始的过程的PID,它也无济于事。
所以我最后编写了这个函数,我在Mac OS X和RedHat Linux上测试过,将运行的进程检索为data.table:
library(data.table)
library(stringr)
# Returns a process list on a Linux or Mac OS X system by calling 'ps' command and
# parsing its output.
processList <- function() {
# Execute ps
ps = robust.system("ps auxww")
if (ps$exitStatus != 0) {
print(ps)
return(NA)
}
# Turn into data.table
ps$stdout = str_trim(ps$stdout)
ncols = str_count(ps$stdout[1], "[ ]+") + 1
procs = str_split_fixed(ps$stdout, "[ ]+", ncols)
ps = as.data.table(procs[2:nrow(procs),])
setnames(ps, 1:ncols, procs[1,])
rm(ncols, procs)
# Convert relevant columns to friendlier data types.
# Rename Mac OS X style "TT" to "TTY" and "STARTED" to "START" as well.
if ("PID" %chin% colnames(ps)) {
ps[,PID:=as.integer(as.character(PID))]
}
if ("%CPU" %chin% colnames(ps)) {
setnames(ps, "%CPU", "percentCPU")
ps[,percentCPU:=as.numeric(percentCPU)]
}
if ("%MEM" %chin% colnames(ps)) {
setnames(ps, "%MEM", "percentMEM")
ps[,percentMEM:=as.numeric(percentMEM)]
}
if ("TT" %chin% colnames(ps)) {
setnames(ps, "TT", "TTY")
}
if ("STARTED" %chin% colnames(ps)) {
setnames(ps, "STARTED", "START")
}
if ("COMMAND" %chin% colnames(ps)) {
ps[,COMMAND:=as.character(COMMAND)]
}
return(ps)
}
请注意,它使用robust.system,因此您也需要它。