forked from r-lib/ps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.Rmd
475 lines (351 loc) · 11.1 KB
/
README.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
---
output:
github_document:
toc: true
toc_depth: 3
includes:
before_body: header.md
---
```{r echo = FALSE}
options(width = 100)
suppressWarnings(suppressPackageStartupMessages(suppressMessages(library(dplyr))))
suppressWarnings(suppressMessages(library(pillar)))
```
## Installation
You can install the released version of ps from
[CRAN](https://CRAN.R-project.org) with:
``` r
install.packages("ps")
```
```{r}
library(ps)
library(pillar) # nicer printing of data frames
```
## Supported platforms
ps currently supports Windows (from Vista), macOS and Linux systems.
On unsupported platforms the package can be installed and loaded, but
all of its functions fail with an error of class `"not_implemented"`.
## Listing all processes
`ps_pids()` returns all process ids on the system. This can be useful to
iterate over all processes.
```{r}
ps_pids()[1:20]
```
`ps()` returns a data frame, with data about each process. It contains a
handle to each process, in the `ps_handle` column, you can use these to
perform more queries on the processes.
```{r}
ps()
```
## Process API
This is a short summary of the API. Please see the documentation of the
various methods for details, in particular regarding handles to finished
processes and pid reuse. See also "Finished and zombie processes"
and "pid reuse" below.
`ps_handle(pid)` creates a process handle for the supplied process id.
If `pid` is omitted, a handle to the calling process is returned:
```{r}
p <- ps_handle()
p
```
### Query functions
`ps_pid(p)` returns the pid of the process.
```{r}
ps_pid(p)
```
`ps_create_time()` returns the creation time of the process (according to
the OS).
```{r}
ps_create_time(p)
```
The process id and the creation time uniquely identify a process in a
system. ps uses them to make sure that it reports information about, and
manipulates the correct process.
`ps_is_running(p)` returns whether `p` is still running. It handles pid
reuse safely.
```{r}
ps_is_running(p)
```
`ps_ppid(p)` returns the pid of the parent of `p`.
```{r}
ps_ppid(p)
```
`ps_parent(p)` returns a process handle to the parent process of `p`.
```{r}
ps_parent(p)
```
`ps_name(p)` returns the name of the program `p` is running.
```{r}
ps_name(p)
```
`ps_exe(p)` returns the full path to the executable the `p` is running.
```{r}
ps_exe(p)
```
`ps_cmdline(p)` returns the command line (executable and arguments) of `p`.
```{r}
ps_cmdline(p)
```
`ps_status(p)` returns the status of the process. Possible values are OS
dependent, but typically there is `"running"` and `"stopped"`.
```{r}
ps_status(p)
```
`ps_username(p)` returns the name of the user the process belongs to.
```{r}
ps_username(p)
```
`ps_uids(p)` and `ps_gids(p)` return the real, effective and saved user
ids of the process. They are only implemented on POSIX systems.
```{r}
if (ps_os_type()[["POSIX"]]) ps_uids(p)
if (ps_os_type()[["POSIX"]]) ps_gids(p)
```
`ps_cwd(p)` returns the current working directory of the process.
```{r}
ps_cwd(p)
```
`ps_terminal(p)` returns the name of the terminal of the process, if any.
For processes without a terminal, and on Windows it returns `NA_character_`.
```{r}
ps_terminal(p)
```
`ps_environ(p)` returns the environment variables of the process.
`ps_environ_raw(p)` does the same, in a different form. Typically they
reflect the environment variables at the start of the process.
```{r}
ps_environ(p)[c("TERM", "USER", "SHELL", "R_HOME")]
```
`ps_num_threads(p)` returns the current number of threads of the process.
```{r}
ps_num_threads(p)
```
`ps_cpu_times(p)` returns the CPU times of the process, similarly to
`proc.time()`.
```{r}
ps_cpu_times(p)
```
`ps_memory_info(p)` returns memory usage information. See the manual for
details.
```{r}
ps_memory_info(p)
```
`ps_children(p)` lists all child processes (potentially recursively) of
the current process.
```{r}
ps_children(ps_parent(p))
```
`ps_num_fds(p)` returns the number of open file descriptors (handles on
Windows):
```{r}
ps_num_fds(p)
f <- file(tmp <- tempfile(), "w")
ps_num_fds(p)
close(f)
unlink(tmp)
```
`ps_open_files(p)` lists all open files:
```{r}
ps_open_files(p)
f <- file(tmp <- tempfile(), "w")
ps_open_files(p)
close(f)
unlink(tmp)
ps_open_files(p)
```
### Process manipulation
`ps_suspend(p)` suspends (stops) the process. On POSIX it sends a SIGSTOP
signal. On Windows it stops all threads.
`ps_resume(p)` resumes the process. On POSIX it sends a SIGCONT signal. On
Windows it resumes all stopped threads.
`ps_send_signal(p)` sends a signal to the process. It is implemented on
POSIX systems only. It makes an effort to work around pid reuse.
`ps_terminate(p)` send SIGTERM to the process. On POSIX systems only.
`ps_kill(p)` terminates the process. Sends `SIGKILL` on POSIX systems,
uses `TerminateProcess()` on Windows. It make an effort to work around
pid reuse.
`ps_interrupt(p)` interrupts a process. It sends a `SIGINT` signal on
POSIX systems, and it can send a CTRL+C or a CTRL+BREAK event on Windows.
## Finished and zombie processes
ps handles finished and Zombie processes as much as possible.
The essential `ps_pid()`, `ps_create_time()`, `ps_is_running()` functions
and the `format()` and `print()` methods work for all processes, including
finished and zombie processes. Other functions fail with an error of class
`"no_such_process"` for finished processes.
The `ps_ppid()`, `ps_parent()`, `ps_children()`, `ps_name()`,
`ps_status()`, `ps_username()`, `ps_uids()`, `ps_gids()`, `ps_terminal()`,
`ps_children()` and the signal sending functions work properly for
zombie processes. Other functions fail with `"zombie_process"` error.
## Pid reuse
ps functions handle pid reuse as well as technically possible.
The query functions never return information about the wrong process, even
if the process has finished and its process id was re-assigned.
On Windows, the process manipulation functions never manipulate the wrong
process.
On POSIX systems, this is technically impossible, it is not possible to
send a signal to a process without creating a race condition. In ps the
time window of the race condition is very small, a few microseconds, and
the process would need to finish, _and_ the OS would need to reuse its pid
within this time window to create problems. This is very unlikely to
happen.
## Recipes
In the spirit of [psutil recipes](http://psutil.readthedocs.io/en/latest/#recipes).
### Find process by name
Using `ps()` and dplyr:
```{r}
library(dplyr)
find_procs_by_name <- function(name) {
ps() %>%
filter(name == !!name) %>%
pull(ps_handle)
}
find_procs_by_name("R")
```
Without creating the full table of processes:
```{r}
find_procs_by_name <- function(name) {
procs <- lapply(ps_pids(), function(p) {
tryCatch({
h <- ps_handle(p)
if (ps_name(h) == name) h else NULL },
no_such_process = function(e) NULL,
access_denied = function(e) NULL
)
})
procs[!vapply(procs, is.null, logical(1))]
}
find_procs_by_name("R")
```
### Wait for a process to finish
On POSIX, there is no good way to wait for non-child processes to finish,
so we need to write a sleep-wait loop to do it. (On Windows, and BSD
systems, including macOS, there are better solutions.)
```{r}
as_secs <- function(x) as.numeric(x, units = "secs")
wait_for_process <- function(proc, timeout = Inf, sleep = 0.1) {
sleep <- as_secs(sleep)
deadline <- Sys.time() + timeout
while (ps_is_running(proc) && (timeout == Inf || Sys.time() < deadline)) {
to <- min(as_secs(deadline - Sys.time()), sleep)
Sys.sleep(to)
}
! ps_is_running(proc)
}
px <- processx::process$new("sleep", "2")
p <- ps_handle(px$get_pid())
wait_for_process(p, 1)
wait_for_process(p)
```
### Wait for several processes to finish
This is similar, but we need to wait on all processes in a loop.
```{r}
wait_for_processes <- function(procs, timeout = Inf) {
gone <- list()
alive <- procs
deadline <- Sys.time() + timeout
check_gone <- function(proc, timeout) {
proc_gone <- wait_for_process(proc, timeout = timeout)
if (proc_gone) {
gone <<- c(gone, list(proc))
alive <<- setdiff(alive, list(proc))
}
}
while (length(alive)) {
if (timeout <= 0) break
for (proc in alive) {
max_timeout <- 1 / length(alive)
if (timeout != Inf) {
timeout <- min(as_secs(deadline - Sys.time()), max_timeout)
if (timeout <= 0) break
check_gone(proc, timeout)
} else {
check_gone(proc, max_timeout)
}
}
}
list(gone = gone, alive = alive)
}
px1 <- processx::process$new("sleep", "10")
px2 <- processx::process$new("sleep", "10")
px3 <- processx::process$new("sleep", "1")
px4 <- processx::process$new("sleep", "1")
p1 <- ps_handle(px1$get_pid())
p2 <- ps_handle(px2$get_pid())
p3 <- ps_handle(px3$get_pid())
p4 <- ps_handle(px4$get_pid())
wait_for_processes(list(p1, p2, p3, p4), timeout = 2)
```
### Kill process tree
This sends a signal, so it'll only work on Unix. Use `ps_kill()`
instead of `ps_send_signal()` on Windows.
```{r}
kill_proc_tree <- function(pid, sig = signals()$SIGTERM,
include_parent = TRUE) {
if (pid == Sys.getpid() && include_parent) stop("I refuse to kill myself")
parent <- ps_handle(pid)
children <- ps_children(parent, recursive = TRUE)
if (include_parent) children <- c(children, parent)
for (p in children) ps_send_signal(p, sig)
wait_for_processes(children, timeout = 0.1)
}
p1 <- processx::process$new("sleep", "10")
p2 <- processx::process$new("sleep", "10")
p3 <- processx::process$new("sleep", "10")
kill_proc_tree(Sys.getpid(), include_parent = FALSE)
```
### Terminate children
Note, that some R IDEs, including RStudio, run a multithreaded R process,
and other threads may start processes as well. `reap_children()` will clean
up all these as well, potentially causing the IDE to misbehave or crash.
```{r}
reap_children <- function(timeout = 3) {
procs <- ps_children(ps_handle())
## SIGTERM
lapply(procs, ps_terminate)
ga <- wait_for_processes(procs, timeout = timeout)
## SIGKILL to the survivers
if (length(ga$alive)) lapply(ga$alive, ps_kill)
ga2 <- wait_for_processes(ga$alive, timeout = timeout)
## Some might still survive
list(gone = c(ga$gone, ga2$gone), alive = ga2$alive)
}
pxs <- replicate(3, processx::process$new("sleep", "3"))
reap_children()
```
### Filtering and sorting processes
Process name ending with "sh":
```{r}
ps() %>%
filter(grepl("sh$", name))
```
Processes owned by user:
```{r}
ps() %>%
filter(username == Sys.info()[["user"]]) %>%
select(pid, name)
```
Processes consuming more than 100MB of memory:
```{r}
ps() %>%
filter(rss > 100 * 1024 * 1024)
```
Top 3 memory consuming processes:
```{r}
ps() %>%
top_n(3, rss) %>%
arrange(desc(rss))
```
Top 3 processes which consumed the most CPU time:
```{r}
ps() %>%
mutate(cpu_time = user + system) %>%
top_n(3, cpu_time) %>%
arrange(desc(cpu_time)) %>%
select(pid, name, cpu_time)
```
## Code of Conduct
Please note that the ps project is released with a
[Contributor Code of Conduct](https://ps.r-lib.org/CODE_OF_CONDUCT.html).
By contributing to this project, you agree to abide by its terms.
## License
MIT © RStudio