为什么当我终止远程主机上的进程时连接中断?

我通过sshlogin到远程主机(debian)并执行一个像这样的命令

ssh user@remote_host "ps -ef | grep process_name | grep -v grep | awk {'print $2'} | xargs kill -9' 

那么连接中断。

我ping远程主机,不能收到任何响应,如networking没有连接。 但是,当我重新启动远程主机(关机和开机),一切都很好。 我承诺杀死的进程只有我写的程序,它的父进程是“初始化”进程(如果进程运行在fg中,并被杀死,一切正常)。 有谁知道为什么发生?

我想知道你给我们的命令甚至跑了没有错误。 正如在另一个答案中提到的,你传递了太多的东西给xargs / kill ,他们把它当作垃圾。

使用这样的东西来提取只有PID杀死它

 ps -ef | grep process_name | grep -v grep | awk '{print $3}' | xargs kill -9 

ps -ef | grep process_name | grep -v grep ps -ef | grep process_name | grep -v grep不仅给出了你想要杀死的pid ,而且给出了其他的信息,比如过程的uid,命令等,这些信息可能会意外地杀死任何东西。 更可惜的是,它的ppid (父亲pid,对你来说是1)也显示出来了,那么你知道会发生什么。

你可以试试

 ssh user@remote_host "pkill process_name" 

要么

 ssh user@remote_host "ps -eo pid,cmd | grep process_name | grep -v grep | cut -d' ' -f2 | xargs kill -9" 

或者你可以先得到它的输出:

 ssh user@remote_host "ps -ef | grep process_name | grep -v grep" 

然后自己过滤pid。