/* File: ~liux/public_html/courses/cop4610/examples/simple-cd.cc
Purpose: Demonstrate how to use chdir, getenv and getcwd system calls
for COP 4610
Author: Xiuwen Liu, based on an example in Advanced Programming
in the UNIX Environment, by W. Richard Stevens,
Addison-Wesley, 1992
On the web:
http://www.cs.fsu.edu/~liux/courses/cop4610/examples/simple-cd.cc
Complie
g++ -o simple-cd simple-cd.cc
*/
#include
#include
#include
#include
#include
#include
#include
#include
#define MAX_LINE 512
#define MAX_ARG 50
int Parse_Command(char *buf, char *argv_list[]);
void sig_handler(int); /* A signal handler */
int interrupted;
pid_t my_pid;
int main(void)
{
char buf[MAX_LINE];
pid_t pid;
int status;
char *my_argv[MAX_ARG];
int my_argc;
int i;
char ch;
my_pid = getpid(); /* Get my process id */
if (signal(SIGINT, sig_handler) == SIG_ERR)
cerr << my_pid << " Could not catch signal SIGINT.\n";
do {
getcwd(buf,MAX_LINE);
cout <<"Your current working directory is \n\t" << buf <<"\n";
cout << "Do you want to change it ? ";
interrupted = 0;
cout.flush();
cin.getline((char *)buf,MAX_LINE);
cin.clear();
/*sleep(1);
cout << "Now buffer is " << buf;*/
if (interrupted) {
cin.clear();
cout << endl;
/* cin >> ch;
cout << ch;*/
continue;
}
if (buf[0] == 'N' || buf[0] == 'n') break;
cout << "Please enter your desired directory: ";
interrupted = 0;
buf[0]='\0';
/* cin >> ch; */
cin.clear();
cin.getline((char *)buf,MAX_LINE);
/* cout << "Enter directory: " << buf; */
if (interrupted) {
cin.clear();
cout << endl;
/* cin >> i; */
continue;
}
if (buf[0] == '\0') {
my_argc = 0;
}
else {
if (buf[strlen(buf)-1] != '/')
strcat(buf,"/");
my_argc = Parse_Command(buf, my_argv);
}
if (my_argc > 1) {
cout <<"cd: Too many parameters.\n";
continue;
}
if (my_argc == 0) {
my_argv[0] = getenv("HOME");
if (my_argv[0] != NULL)
my_argc = 1;
else {
cerr<<"cd: could not get home directory.\n";
continue;
}
}
if (chdir(my_argv[0]) < 0) {
perror("cd");
}
} while(1);
return 0;
}
int Parse_Command(char *buf, char *argv_list[])
{
int now_argc = 0;
char *bufp;
bufp = strtok(buf, " \t");
argv_list[now_argc] = bufp;
if (bufp == NULL) return now_argc;
now_argc++;
while (bufp != NULL && now_argc < MAX_ARG) {
bufp = strtok(NULL," \t");
argv_list[now_argc++] = bufp;
}
now_argc --; /* Because the last one is an empty string */
if (now_argc >= MAX_ARG) {
cerr<<"Argument list too long.\n";
}
return now_argc;
}
void sig_handler(int signo) /* signo: Signal number defined in */
{
signal(signo,sig_handler); /* Refine the signal handler,
otherwise, the system resets to the
default action */
switch(signo) {
case SIGINT:
interrupted = 1;
cout << my_pid << ": Receieved signal SIGINT = " << signo << ".\n";
break;
default:
cout<