Skip to content

Commit

Permalink
fix: add command for forcibly stopping a session
Browse files Browse the repository at this point in the history
  • Loading branch information
asforest committed Apr 12, 2023
1 parent 43c29ac commit 946bb12
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 3 deletions.
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -367,18 +367,24 @@ MShell有4个大指令,分别是:
# 别名:d
/ms disconnect

# 强制断开一个会话的所有连接
# 断开一个会话的所有连接
# 别名:d
/ms disconnect <pid>

# 强制结束当前连接中的会话
# 结束当前连接中的会话
# 别名:k
/ms kill

# 强制结束一个会话
# 结束一个会话
# 别名:k
/ms kill <pid>

# 使用系统命令行来强制结束一个会话
# 别名:fk
# 当会话无法使用kill命令正常终止时可以使用forcekill来强制结束(此命令仅支持和Linux平台)
# 此命令在Windows使用`taskkill /F /PID $pid`完成,Linux平台使用`kill -9 $pid`完成
/ms forcekill <pid>

# 显示所有运行中的会话
# 别名:l
/ms list
Expand Down
33 changes: 33 additions & 0 deletions src/main/kotlin/command/MainCommand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import com.github.asforest.mshell.permission.PresetGrants
import com.github.asforest.mshell.session.Session
import com.github.asforest.mshell.session.SessionManager
import com.github.asforest.mshell.util.MShellUtils.buildUsage
import java.util.*
import java.util.concurrent.TimeUnit

object MainCommand : TreeCommand()
{
Expand Down Expand Up @@ -93,6 +95,37 @@ object MainCommand : TreeCommand()
}
}

@Command(desc = "给指定的会话发送kill信号", aliases = ["fk"], permission = Admin or User)
suspend fun CallingContext.forcekill(pid: Long)
{
withCatch {
val session = pidToSession(pid)

// 检查权限
checkPermission(session.preset) ?: throw NoPermissionToKillSessionException(pid)

val os = System.getProperty("os.name").lowercase(Locale.getDefault())

val cli = if ("windows" in os) {
"taskkill /F /PID $pid"
} else if ("linux" in os) {
"kill -9 /F /PID $pid"
} else {
throw ForceKillException("当前操作系统 $os 不支持使用 forcekill 命令")
}

val process = ProcessBuilder().command(cli).start()

if (!process.waitFor(5, TimeUnit.SECONDS))
throw ForceKillException("出现错误,forcekill 命令行的执行时间超时!请考虑手动结束 forcekill 的进程(pid: ${process.pid()})")

if (process.exitValue() != 0)
throw ForceKillException("出现错误,forcekill 命令行的返回值不等于0,实际返回值为:${process.exitValue()}。原始命令行为:$cli")

sendMessage("已强制结束会话 $pid")
}
}

@Command(desc = "连接到一个会话", aliases = ["c"], permission = Admin or User)
suspend fun CallingContext.connect(pid: Long)
{
Expand Down
6 changes: 6 additions & 0 deletions src/main/kotlin/exception/business/ForceKillException.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.github.asforest.mshell.exception.business

import com.github.asforest.mshell.exception.AbstractBusinessException

class ForceKillException(reason: String)
: AbstractBusinessException(reason)

0 comments on commit 946bb12

Please sign in to comment.