将原来的例子进行了修改,可以上下翻页显示进程信息,并杀死选中的进程
- #include <curses.h>
- #include <string.h>
- #define MAXROW 1000 //最大行数
- #define MAXCOL 500 //最大列数
- WINDOW *scrn; //窗口
- char cmdoutlines[MAXROW][MAXCOL]; //存储ps -ax输出的进程信息,每行为一个进程
- int ncmdlines = 0; //总进程信息数
- int winrow = 0; //当前光标位置
- int curcmdline = 0; //当前页面输出进程的起始索引
- /*当前行高亮*/
- void highlight(int line)
- {
- attron(A_BOLD); //输出粗体字
-
- mvaddstr(winrow, 0, cmdoutlines[line]);
- move(winrow, 0);
-
- attroff(A_BOLD);
-
- refresh();
- }
- /*获取进程信息*/
- void runpsax()
- {
- FILE *p;
- char ln[MAXCOL];
- int row;
- char *tmp;
-
- p = popen("ps ax", "r");
-
- for (row = 0; row < MAXROW; row++)
- {
- tmp = fgets(ln, MAXCOL, p);
- if ( tmp == NULL)
- break;
- strncpy(cmdoutlines[row], ln, COLS);
- cmdoutlines[row][MAXCOL-1] = 0;
- }
-
- ncmdlines = row; //总进程信息数
-
- pclose(p);
- }
- /*显示进程信息,startline是数组中的索引*/
- void showlines(int startline)
- {
- clear();
-
- if (startline < 0)
- {
- startline = 0;
- }
- else if(startline > ncmdlines)
- {
- startline = ncmdlines;
- }
-
- if (ncmdlines - startline < LINES)
- {
- if (ncmdlines > LINES)
- startline = ncmdlines - LINES;
- else
- startline = 0;
- }
-
- curcmdline = startline; //开始输出信息的索引
-
- //在当前页面输出信息
- for (winrow=0; winrow < LINES && startline < ncmdlines; winrow++, startline++)
- {
- mvaddstr(winrow, 0, cmdoutlines[startline]);
- }
-
- refresh();
- --winrow;
- --startline;
- move(winrow, 0);
- }
- //光标上移
- void updown(int inc)
- {
- int tmp = winrow + inc;
-
- if (tmp < 0)
- {
- showlines(curcmdline+tmp);
- winrow = 0;
- highlight(curcmdline);
- move(0, 0);
- }
- else if ( (tmp >= 0) && (tmp < LINES))
- {
- mvaddstr(winrow, 0, cmdoutlines[curcmdline+winrow]);
- winrow = tmp;
- highlight(curcmdline+tmp);
- }
- else
- {
- showlines(curcmdline+inc);
- highlight(curcmdline+winrow);
- }
- }
- void rerun()
- {
- runpsax();
- showlines(0);
- }
- void prockill() //杀死进程
- {
- char *pid;
- pid =strtok(cmdoutlines[curcmdline+winrow], " ");
- kill(atoi(pid), 9);
-
- rerun();
- }
- int main()
- {
- char c;
- bool quit = false;
- scrn = initscr();
- noecho();
- cbreak();
-
- runpsax();
- showlines(0);
-
- while(!quit)
- {
- c = getch();
-
- switch (c)
- {
- case 'u':
- updown(-1);
- break;
- case 'd':
- updown(1);
- break;
- case 'r':
- rerun();
- break;
- case 'k':
- prockill();
- break;
- case 'q':
- quit = true;
- break;
- default:
- break;
- }
- }
-
- endwin();
- }
阅读(1975) | 评论(1) | 转发(0) |