wide/output/processes.go

91 lines
1.9 KiB
Go
Raw Normal View History

2014-09-16 13:32:55 +04:00
package output
import (
"os"
2014-09-19 15:21:13 +04:00
"sync"
2014-09-16 13:32:55 +04:00
2014-09-19 15:21:13 +04:00
"github.com/b3log/wide/session"
2014-09-16 13:32:55 +04:00
"github.com/golang/glog"
)
// 所有用户正在运行的程序进程集.
// <sid, []*os.Process>
type procs map[string][]*os.Process
var processes = procs{}
2014-09-19 15:21:13 +04:00
// 排它锁,防止并发修改.
var mutex sync.Mutex
2014-09-16 13:32:55 +04:00
// 添加用户执行进程.
2014-09-19 15:21:13 +04:00
func (procs *procs) add(wSession *session.WideSession, proc *os.Process) {
mutex.Lock()
defer mutex.Unlock()
sid := wSession.Id
2014-09-16 13:32:55 +04:00
userProcesses := (*procs)[sid]
userProcesses = append(userProcesses, proc)
(*procs)[sid] = userProcesses
2014-09-19 15:21:13 +04:00
// 会话关联进程
wSession.SetProcesses(userProcesses)
2014-09-16 13:32:55 +04:00
glog.V(3).Infof("Session [%s] has [%d] processes", sid, len((*procs)[sid]))
}
// 移除用户执行进程.
2014-09-19 15:21:13 +04:00
func (procs *procs) remove(wSession *session.WideSession, proc *os.Process) {
mutex.Lock()
defer mutex.Unlock()
sid := wSession.Id
2014-09-16 13:32:55 +04:00
userProcesses := (*procs)[sid]
var newProcesses []*os.Process
for i, p := range userProcesses {
if p.Pid == proc.Pid {
newProcesses = append(userProcesses[:i], userProcesses[i+1:]...)
(*procs)[sid] = newProcesses
2014-09-19 15:21:13 +04:00
// 会话关联进程
wSession.SetProcesses(newProcesses)
2014-09-16 13:32:55 +04:00
glog.V(3).Infof("Session [%s] has [%d] processes", sid, len((*procs)[sid]))
return
}
}
}
// 结束用户正在执行的进程.
2014-09-19 15:21:13 +04:00
func (procs *procs) kill(wSession *session.WideSession, pid int) {
mutex.Lock()
defer mutex.Unlock()
sid := wSession.Id
2014-09-16 13:32:55 +04:00
2014-09-19 15:21:13 +04:00
userProcesses := (*procs)[sid]
for i, p := range userProcesses {
2014-09-16 13:32:55 +04:00
if p.Pid == pid {
if err := p.Kill(); nil != err {
glog.Error("Kill a process [pid=%d] of session [%s] failed [error=%v]", pid, sid, err)
} else {
2014-09-19 15:21:13 +04:00
var newProcesses []*os.Process
newProcesses = append(userProcesses[:i], userProcesses[i+1:]...)
(*procs)[sid] = newProcesses
// 会话关联进程
wSession.SetProcesses(newProcesses)
2014-09-16 13:32:55 +04:00
glog.V(3).Infof("Killed a process [pid=%d] of session [%s]", pid, sid)
}
2014-09-22 13:44:07 +04:00
return
2014-09-16 13:32:55 +04:00
}
}
}