您的位置:首页 > 运维架构 > Linux

OS 进程管理

2017-06-30 17:31 316 查看

OS 课设:进程管理器

设计要求:

设计一个进程管理程序,具体功能包括:

1、列出系统当前所有进程。

2、列出隶属于该进程的所有线程。

3、如果进程有窗口,可以显示和隐藏窗口。

4、强行结束指定进程。

设计报告:

1、进程和线程的概念。

2、如何读取系统进程列表。

3、如何读取进程的线程列表。

4、如何向进程发送消息。

5、如何强行结束进程。

分析:

列出所有进程

ps -e


列出所有某进程的所有线程:

ps mp pid -o THREAD,TID,PID


如果某进程有窗口,可以显示或隐藏

这个是最难的,我知道windows可以通过想进程发送句柄消息,实现该控制。

但对于linux,我只看过unix环境编程,大多没有讲述linux的gui机制。对于x11,我也查了相关资料,没有发现怎么实现。如果x11有,那么这个更好。

查到一些窗口管理程序,最开始是xdotool,我试了一下,并不是太好用的,很多试验没有成功。接着是wmctrl这个很简单,也很好用,但在最小化窗口时,要注意一下。

隐藏:

最小化在移除了max*之后才有效

wmctrl -r $WINDOW_NAME -b remove,maximized_horz #$WINDOW_NAME是窗口的名字
wmctrl -r $WINDOW_NAME -b remove,maximized_vert
wmctrl -r $WINDOW_NAME -b toggle,shaded #minimize


显示

wmctrl -a $WINDOW_NAME


强行结束进程

kill pid


设计报告,向进程发送消息,待差unix环境高级编程

code:

#include <iostream>

#include <cstdlib>

#include <string>

using namespace std;

int main()
{
cout<<"processes manager"<<endl;
int op=0;
string sop;
string pid;
int running=1;
while(running)
{
cout<<"select option(only integer):\n \
0---show processes\n \
1---show thread\n \
2---kill process\n \
3---show window(if having a window in that pid)\n \
4---hide window(if having a window in that pid)\n \
others---exit"<<endl;
cin>>sop;
try{
op=std::stoi(sop);
}catch(...)
{
cout<<"input error"<<endl;
cout<<"exit"<<endl;
break;
}

switch(op)
{
case 0:
system("ps -e");
break;
case 1:
cout<<"input the pid"<<endl;
cin>>pid;
{
string tmp="ps mp "+pid;
tmp+=" -o THREAD,pid,tid";
cout<<tmp<<endl;
system(tmp.c_str());
}
break;
case 2:
cout<<"input pid:"<<endl;
cin>>pid;
{
string tmp="kill "+pid;
cout<<tmp<<endl;
system(tmp.c_str());
}
break;
case 3:
cout<<"input pid:"<<endl;
cin>>pid;
{
string tmp="./win.sh show "+pid;
cout<<tmp<<endl;
system(tmp.c_str());
}
break;
case 4:
cout<<"input pid:"<<endl;
cin>>pid;
{
string tmp="./win.sh hide "+pid;
cout<<tmp<<endl;
system(tmp.c_str());
}
break;

default:
running=0;
break;
}
}
return 0;
}


script:

#!/bin/bash
#show/hide windows by pid
#if known the pid of window use this
#wmctrl -a $(wmctrl -lp | awk -vpid=20809 '$3==pid {print $5}')

#paramter 1 is the mode of hide/show
#paramter 2 is the pid of process

MODE=$1
PID=$2
#等号左右不能有空
WINDOW_NAME="$(wmctrl -lp | awk -vpid=$PID '$3==pid {print $5}')"

EXAMPLE1="wmctrl show $PID --show the window which pid==$PID"
EXAMPLE2="wmctrl hide $PID --hide the window which pid==$PID"

if [ "$MODE" == '' -o "$PID" == '' ];then
echo "input error,there are some examples:"
echo $EXAMPLE1
echo $EXAMPLE2
exit
fi

if [ "$WINDOW_NAME" != '' ];
then
if [ "$MODE" == "hide" ];then
wmctrl -r $WINDOW_NAME -b remove,maximized_horz
wmctrl -r $WINDOW_NAME -b remove,maximized_vert
wmctrl -r $WINDOW_NAME -b toggle,shaded
elif [ "$MODE" == "show" ];then
wmctrl -a $WINDOW_NAME
else
echo "mode error"
fi
#error
else
echo "error :get nothing about this pid or this process is not gui"
fi


参考

最小化在移除了max*之后才有效
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息