如何使用端口号从R中杀死Windows应用程序?

时间:2019-01-14 13:48:39

标签: r cmd

我是一个愚蠢的问题。如何从R中传递以下Windows命令(以杀死在1234端口上运行的进程):

for /f "tokens=5" %a in ('netstat -aon ^| find ":1234" ^| find "LISTENING"')
    do taskkill /f /pid %a

到目前为止,我已经尝试过...

# Create the string
kill <- "for /f \"tokens=5\" %a in ('netstat -aon ^| find \":1234\" ^| find \"LISTENING\"') do taskkill /f /pid %a"

# Check
cat(shQuote(kill, type="cmd"))
# "for /f \"tokens=5\" %a in ('netstat -aon ^| find \":1234\" ^| find \"LISTENING\"') do taskkill /f /pid %a"

# Run the cmd
system(shQuote(kill, type="cmd"), wait = F)

# Warning message:
#   In system(shQuote(kill, type = "cmd"), wait = F) :
#   '"for /f \"tokens=5\" 0x0p+0 in ('netstat -aon ^| find \":1234\" ^| find \"LISTENING\"') do taskkill /f /pid 0x0p+0"' not found

编辑:我的帮助

我得到的引号组合使(cat)字符串与win命令相同。

kill <- 'for /f "tokens=5" %a in (\'netstat -aon ^| find ":1234" ^| find "LISTENING"\') do taskkill /f /pid %a'
cat(kill)
# From Cat:    for /f "tokens=5" %a in ('netstat -aon ^| find ":1234" ^| find "LISTENING"') do taskkill /f /pid %a
# Win Command: for /f "tokens=5" %a in ('netstat -aon ^| find ":1234" ^| find "LISTENING"') do taskkill /f /pid %a

其他:

以下代码将在端口1234上运行一个闪亮的应用程序。试图从另一个R会话中杀死该应用程序。

library(shiny)

ui <- fluidPage(

)

server <- function(input, output, session) {

}

shinyApp(ui, server, options = list(launch.browser = TRUE, port = 1234))

1 个答案:

答案 0 :(得分:2)

感谢@HenrikB的建议。是的,下面的带有shell()函数的代码正在工作...

# Create the string
kill <- 'for /f "tokens=5" %a in (\'netstat -aon ^| find ":1234" ^| find "LISTENING"\') do taskkill /f /pid %a'

# Check
cat(kill)
# From Cat:    for /f "tokens=5" %a in ('netstat -aon ^| find ":1234" ^| find "LISTENING"') do taskkill /f /pid %a
# Win Command: for /f "tokens=5" %a in ('netstat -aon ^| find ":1234" ^| find "LISTENING"') do taskkill /f /pid %a

# Run the cmd
shell(kill)
# E:\Raja\Installed_Software\R-3.5.1>taskkill /f /pid 18772 
# SUCCESS: The process with PID 18772 has been terminated.