Created
November 9, 2014 21:46
-
-
Save jamiefolson/6d5890718afec1ad1932 to your computer and use it in GitHub Desktop.
Getting process ID and running `top` from R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Run the Linux top command | |
#' | |
#' @param user character value indicating a system user to filter tasks by | |
#' @param pid one or more process ids to retrieve | |
#' | |
#' @return | |
#' A data.frame value containing the information returned by top. | |
#' | |
sys.top <- function(user=Sys.getenv("USER"),pid=NULL){ | |
# Run top in batch mode "-b" once "-n 1" | |
top_cmd <- paste("top -b -n 1", | |
if(!is.null(user))paste("-U",user), | |
if(!is.null(pid))paste("-p",paste(pid,collapse=" "))) | |
top_out <- system(top_cmd, intern=TRUE ) | |
# Drop the summary data from the results | |
top_data <- top_out[-(1:7)] | |
# Grab the field names, dropping the first empty value | |
top_names <- strsplit(top_out[7],"[[:space:]]+")[[1]][-1] | |
top_data <- top_data[nchar(top_data) > 0] | |
# fields are space delimited | |
top_data <- strsplit(top_data,"[[:space:]]+") | |
top_ncols <- length(top_names) | |
# Drop any empty rows at the bottom | |
top_data <- lapply(top_data, | |
function(x)x[nchar(x)>0]) | |
# paste back together any "Command" values that we split up | |
top_data <- lapply(top_data,function(x)c(x[1:(top_ncols-1)], | |
paste(x[top_ncols:length(x)],collapse=" "))) | |
top_df <- as.data.frame(do.call(rbind,top_data)) | |
names(top_df) <- top_names | |
top_df | |
} | |
#' Get the Process ID (PID) for the R session | |
sys.pid <- function(){ | |
system("echo $PPID", intern=TRUE) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment