2

I would like send a signal to a process I started with system or system2 on Linux and Mac OS X. However, going through their documentation I was unable to find any way to find out the pid of the newly started process.

asieira
  • 3,513
  • 3
  • 23
  • 23
  • Unfornate that this has been flagged as a duplicate, since the question that supposedly is the same as this only covers the actual solution for Windows systems. My problem and the answer I ended up providing myself, works for Linux and Mac OS X. – asieira Jul 12 '13 at 13:57

2 Answers2

4

On Windows (maybe elsewhere, too):

system("tasklist", intern=TRUE)

Returns character vector that you could parse to get the PID for each process.

More detailed answers can be found here and here.

Community
  • 1
  • 1
Thomas
  • 43,637
  • 12
  • 109
  • 140
  • Any chance you could provide sample output of this command? Would be great to improve on the code I posted below so that I works on Windows as well. – asieira Jul 05 '13 at 17:49
  • @asieira I just added links to answers that do a better job than I. – Thomas Jul 05 '13 at 18:05
1

Turns out it wasn't as simple as I imagined. The command I was executing started other processes, and the one I needed to kill was further down the process tree. So even if system/system gave me the PID of the process they started, it wouldn't help me.

So I ended up writing this function, that I tested on Mac OS X and RedHat Linux, to retrieve the running processes as a 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)
}

Please note that it uses robust.system, so you'll need that too.

Community
  • 1
  • 1
asieira
  • 3,513
  • 3
  • 23
  • 23