
Добавил:
Studfiles2
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Тестовые примеры / ch13 / main_shell / main_shell
.C#include <strstream.h>
#include <thread.h>
#include <string.h>
#include <stdio.h>
#include "mshell.h"
/* collect remote hosts that have server running on it */
extern void* collect_hosts( void* argp );
extern void* display_hosts( void* argp );
extern void* exec_shell( void* argp );
shellObj *funcList[4];
int numFunc = sizeof(funcList)/sizeof(funcList[0]);
rwlock_t rwlck;
/* Quit program */
void* quit_prog( void* argp )
{
return (void*)0;
}
/* Execute one shell command on a host */
void* getcmd( void* argp )
{
char host[20], cmd[256], cmd2[256];
cout << "shell cmd> " << flush;
cin >> cmd;
cin.getline(cmd2,256);
cout << "host: " << flush;
cin >> host;
if (!cin)
cout << "Inavlid input\n" << flush;
else {
if (strlen(cmd2)) strcat(strcat(cmd," "),cmd2);
strcat(strcat(cmd,"/"),host);
char* ptr = new char[strlen(cmd)+1];
ostrstream(ptr,strlen(cmd)+1) << cmd;
if (thr_create(0,0,exec_shell,ptr,THR_DETACHED,0))
perror("thr_create");
}
return (void*)1;
}
/* Get an user input selection and execute it */
int exec_cmd()
{
char buf[256];
cout << "Selection> " << flush;
cin >> buf;
cout << endl;
if (cin) {
int idx = -1;
istrstream(buf) >> idx;
if (idx >=0 && idx < numFunc)
return funcList[idx]->doit(0);
else cerr << "Invalid input\n";
}
return 0;
}
/* display menu to user */
void display_menu(ostream& os)
{
for (int i=0; i < numFunc; i++)
(void)funcList[i]->usage(os,i);
}
/* initialize read-write lock and dispatch table */
int init_all()
{
if (rwlock_init (&rwlck, USYNC_THREAD, 0)) {
perror("rwlock_init");
return -1;
}
funcList[0] = new shellObj( "Collect host names", collect_hosts);
funcList[1] = new shellObj( "Display host names", display_hosts);
funcList[2] = new shellObj( "Execute a shell command", getcmd, 0);
funcList[3] = new shellObj( "Quit", quit_prog, 0);
return 0;
}
/* main routine */
int main() {
if (init_all() == 0)
do {
display_menu(cerr);
if (!exec_cmd()) break;
} while (1);
thr_exit(0);
return 0;
}
Соседние файлы в папке main_shell