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

Ant*_*ico 6 windows shell r

假设我有一个可执行文件c:\my directory\my file.exe,我希望在我的R脚本开头附近启动,然后在我的R脚本结束附近终止.什么是干净的方式在Windows平台上做到这一点?

我知道R命令喜欢shellshell.exec,但是我不清楚这些将允许干净地捕获进程id然后使用类似pskill函数的东西.还不清楚通过某种管道连接运行这个可执行文件是否更有意义- 或者管道是如何工作的.这个特殊的可执行文件应PATH作为系统变量包含在我的窗口中,因此可以想象该system函数在这里也可能有价值.

另外澄清:捕获进程id可能很重要,因为(至少对我而言)这将用于数据库服务器的可执行文件 - 如果多个数据库服务器当前在同一台机器上运行,则该进程不应该杀死所有这些 - 只是在R脚本开头初始化的那个.

额外信用:假设c:\my directory\my file.exe应该通过实际执行另一个文件来调用c:\my directory\another file.bat- 但是my file.exe需要在R脚本结束时将其杀死.

Ant*_*ico 5

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

# 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 )
Run Code Online (Sandbox Code Playgroud)