Skip to content

Instantly share code, notes, and snippets.

@tilltnet
Last active November 8, 2019 15:42
Show Gist options
  • Save tilltnet/ae691591edaef6f5ac3e768d00b9ca83 to your computer and use it in GitHub Desktop.
Save tilltnet/ae691591edaef6f5ac3e768d00b9ca83 to your computer and use it in GitHub Desktop.
R Script that kills instances of R related to RStudio Sessions
# This script uses lswin.py from sjitech/mac_list_windows_pids to get
# a list of all running RStudio Sessions and their titles.
# https://github.com/sjitech/mac_list_windows_pids
# This script assumes that lswin.py is in your home folder.
# For convenience you should add an alias to your .bshrc or .zshrc file.
# Example alias: alias rkill="RScript ~/kill_rstudio_rsessions.R"
suppressMessages({
library(dplyr, quietly = TRUE)
library(purrr, quietly = TRUE)
library(readr, quietly = TRUE)
})
a <-
system('python ~/lswin.py', TRUE)
suppressWarnings({
processes_df <-
read_fwf(a,
col_positions =
fwf_cols(pid = 7, wid = 7, pos = 24, descr = 200), skip = 2) %>%
map_dfc(trimws)
})
rs_pids <-
processes_df %>%
filter(grepl("\\[RStudio\\]", descr)) %>%
pull(pid) %>%
unique()
rstudio_instances_df <-
map_df(rs_pids,
~{
processes_df %>%
filter(pid == .x) %>%
mutate(descr = gsub("\\[RStudio\\]","", descr),
descr = trimws(descr)) %>%
filter(grepl("hoose|\\/|RStudio", descr))
}) %>%
mutate(no = 1:nrow(.),
descr = strsplit(descr, "\\/") %>% map_chr(~.[length(.)])) %>%
select(no, pid, descr)
print.data.frame(rstudio_instances_df, row.names = FALSE)
cat("Please type in number of RStudio process, to kill its R session.\n")
no_to_kill <-
readLines("stdin", n=1)
if (!no_to_kill %in% rstudio_instances_df$no) {
cat("Invalid input - aborting...") } else {
pid_of_rstudio_to_kill <-
rstudio_instances_df[as.numeric(no_to_kill), ]$pid
child_pids <-
system(paste("pgrep -P", pid_of_rstudio_to_kill),
intern = TRUE) %>%
paste(collapse = "\\|")
pid_to_kill <-
system(paste0('ps -A | grep "', child_pids, '" | grep [r]sess'),
intern = TRUE) %>% strsplit(" ") %>% .[[1]] %>% .[1]
system(paste("kill", pid_to_kill[1]))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment