gpt4 book ai didi

windows - 如何运行一个可执行文件,然后在 Windows 中使用 R 杀死或终止相同的进程

转载 作者:可可西里 更新时间:2023-11-01 13:22:56 24 4
gpt4 key购买 nike

假设我有一个可执行文件存储在 c:\my directory\my file.exe 中,我想在我的 R 脚本开始时启动它,然后在接近结束时终止我的 R 脚本。在 Windows 平台上有哪些简洁的方法可以做到这一点?

我知道像 shellshell.exec 这样的 R 命令,但我不清楚这些是否允许干净地捕获进程 ID 然后使用类似 the pskill function 的东西.也不清楚通过某种 pipe conection 运行此可执行文件是否更有意义- 或者那个管道是如何工作的。这个特定的可执行文件应该作为系统变量包含在我的 Windows PATH 中,因此可以想象 system 函数在这里也可能有值(value)。

补充说明:捕获进程 ID 可能很重要,因为(至少对我而言)这将用于数据库服务器的可执行文件——如果多个数据库服务器当前在同一台机器上运行,进程不应该终止所有这些 - 只是在 R 脚本开始时初始化的那个。

额外的功劳:假设 c:\my directory\my file.exe 应该通过实际执行另一个文件来调用 - c:\my directory\another file.bat - 但它是 my file.exe 需要在 R 脚本的末尾被杀死。

最佳答案

根据收到的其他两个答案,此技术似乎是实现既定目标的合理方法..

# specify executable file
exe.file <- "C:\\Users\\AnthonyD\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"

# capture the result of a `tasklist` system call
before.win.tasklist <- system2( 'tasklist' , stdout = TRUE )

# store all pids before running the process
before.pids <- substr( before.win.tasklist[ -(1:3) ] , 27 , 35 )

# run the process
shell.exec( exe.file )

# capture the result of a `tasklist` system call
after.win.tasklist <- system2( 'tasklist' , stdout = TRUE )

# store all tasks after running the process
after.tasks <- substr( after.win.tasklist[ -(1:3) ] , 1 , 25 )

# store all pids after running the process
after.pids <- substr( after.win.tasklist[ -(1:3) ] , 27 , 35 )

# store the number in the task list containing the PIDs you've just initiated
initiated.pid.positions <- which( !( after.pids %in% before.pids ) )

# remove whitespace
after.tasks <- gsub( " " , "" , after.tasks )

# find the pid position that matches the executable file name
correct.pid.position <-
intersect(
which( after.tasks %in% basename( exe.file ) ) ,
initiated.pid.positions
)


# remove whitespace
correct.pid <- gsub( " " , "" , after.pids[ correct.pid.position ] )

# write the taskkill command line
taskkill.cmd <- paste( "taskkill" , "/PID" , correct.pid )

# wait thirty seconds (so the program fully loads)
Sys.sleep( 30 )

# kill the same process that was loaded
system( taskkill.cmd )

关于windows - 如何运行一个可执行文件,然后在 Windows 中使用 R 杀死或终止相同的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15134848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com