SlideShare a Scribd company logo
1 of 9
Download to read offline
Add a 3rd field help that contains a short help string for each of the commands you were to
implement in assignment #3. Make sure that your array(s) are big enough to handle 5 extra items
beyond your initialization. To save time only include help for exercises 4, 5, 6 and 8 in this
assignment, and use No help for the other entries.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
void ctrlCHandler(int signum)
{
fprintf(stderr,"Command server terminated using Cn");
exit(1);
}
char * fExport(char *cmd, char *tokensleft[])
{
setenv(tokensleft[0],tokensleft[1],1);
return "Command 'export' was received";
}
char * fChdir(char *cmd,char *tokensleft[])
{
int ch=chdir(tokensleft[0]);
if(ch<0)
perror("chdir change of directory not successfuln");
else
printf("chdir change of directory successfuln");
return "Command 'chdir' was receivedn";
}
char * fAccess(char *cmd,char *tokensleft[])
{
int exists =0;
for(int i=0;tokensleft[i]; i++) {
exists =0;
if(access(tokensleft[i],F_OK)==0){
exists = 1;
printf("file %s existsn",tokensleft[i]);
}else{
printf("file %s does not existsn",tokensleft[i]);
}
if (exists == 1){
if(access(tokensleft[i],R_OK)==0) {
printf("file %s is readablen",tokensleft[i]);
}else{printf("file %s is not readablen",tokensleft[i]);}
if(access(tokensleft[i],W_OK)==0) {
printf("file %s is writeablen",tokensleft[i]);
}else{
printf("file %s is not writeablen",tokensleft[i]);
}
if(access(tokensleft[i],X_OK)==0) {
printf("file %s is executeablen",tokensleft[i]);
}else{
printf("file %s is not executeablen",tokensleft[i]);
}
}// exists if
} //for
return "Command 'acsess' was receivedn";
}
char * fChmod(char *cmd,char *tokensleft[])
{
unsigned int octalPerm;
sscanf(tokensleft[0],"%o",&octalPerm);
for(int i=1;tokensleft[i]; i++) {
if(chmod(tokensleft[i],octalPerm)==0 ){
chmod(tokensleft[i],octalPerm);
}else{
printf("Error: %s n",strerror(errno));
}
}
return "Command 'chmod' was received";
}
char * fPath(char *cmd,char *tokensleft[])
{
char *pathLink;
char actualPath[PATH_MAX+1];
char *pointer;
char *bName;
char *dName;
for(int i=0;tokensleft[i]; i++) {
pathLink = tokensleft[i];
pointer =realpath(pathLink,actualPath);
bName = basename(actualPath);
dName = dirname(tokensleft[i]);
if (pointer){
printf("The Real path of %s is: %sn",tokensleft[i],actualPath);
printf("The Dir name path of %s is: %sn",tokensleft[i],dName);
printf("The Base name of %s is: %sn",tokensleft[i],bName);
}else{
printf("Error: %s n",strerror(errno));
}
}
return "Command 'path' was received";
}
char * fTouch(char *cmd,char *tokensleft[])
{
extern int optind,optopt,opterr;
struct FLAG{
bool aFlag;
bool mFlag;
} flags = { false, false };
int t1 = time(NULL), t2 = time(NULL);
int argc = 0;
int flag;
for (int i = 0; tokensleft[i]; i++) {
argc++;
}
while ((flag = getopt(argc, tokensleft, "m:a:")) != -1) {
switch (flag) {
case 'm':
flags.mFlag = true;
t1 = atoi(optarg);
break;
case 'a':
flags.aFlag = true;
t2 = atoi(optarg);
break;
case ':':
if (optopt == 'm') {
flags.mFlag = true;
}
fprintf(stderr, "%c flag is missing an argument. optopt is: %cn", flag, optopt);
break;
case '?':
fprintf(stderr, "%c is an illegal flagn", optopt);
break;
}
}
// Print the flags and times for testing
printf("Flags: -m %d -a %dn", t1, t2);
printf("mFlag: %d aFlag: %dn", flags.mFlag, flags.aFlag);
return "Command 'touch' was received";
}
char * fLn(char *cmd,char *tokensleft[])
{
int opt;
int force = 0;
int symbolic = 0;
int argc =0;
for (int i = 0; tokensleft[i]; i++) {
argc++;
}
while ((opt = getopt(argc, tokensleft, "sf")) != -1) {
switch (opt) {
case 's':
symbolic = 1;
break;
case 'f':
force = 1;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-s] [-f] file1 file2n", tokensleft[0]);
}
}
if (argc - optind != 2) {
fprintf(stderr, "Usage: %s [-s] [-f] file1 file2n", tokensleft[0]);
}
const char *file1 = tokensleft[optind];
const char *file2 = tokensleft[optind+1];
if (force) {
remove(file2);
}
if (symbolic) {
link(file1, file2);
} else {
if (link(file1, file2) != 0) {
perror("Error creating hard link");
}
}
return "Command 'ln' was received";
}
char * fUnset(char *cmd, char *tokensleft[])
{
unsetenv(tokensleft[0]);
return "Command 'unset' was received";
}
char *commands[10]={"export","chdir","access","chmod", "path","touch","ln","unset"} ;
char *(*methods[10])()={fExport,fChdir,fAccess,fChmod,fPath,fTouch,fLn,fUnset};
//Alternate declaration
struct CMDSTRUCT {
char *cmd;
char *(*method)();
}
cmdStruct[]={{"fred",fExport},{"mary",fChdir},{"clark",fAccess},{"sonia",fChmod},{"carlo",f
Path},{"lalo",fTouch},{"samuel",fLn},{"olga",fUnset},{NULL,NULL}} ;
char *interpret(char *cmdline)
{
char **tokens;
char *cmd;
int i;
char *result;
char sysCommand;
tokens=history_tokenize(cmdline); //Split cmdline into individual words.
if(!tokens) return "no response needed";
cmd=tokens[0];
//Detecting commands: table lookup: 2 techniques
//Using the parallel arrays to look up function calls
for(i=0;commands[i];i++)
{
if(strcasecmp(cmd,commands[i])==0) return (methods[i])(cmd,&tokens[1]);
}
//Using struct CMDSTRUCT as an alternative lookup method. Pick either technique, not both
//Note that its possible to create multiple aliases for the same command using either method.
for(i=0;cmdStruct[i].cmd;i++)
if(strcasecmp(cmd,cmdStruct[i].cmd)==0) return (cmdStruct[i].method)(cmd,&tokens[1]);
sysCommand=system(cmdline);
if (sysCommand==-1){
return"command status: fail";
}else if (sysCommand==0){
return"command status: sucsess";}
}
int main(int argc, char * argv[],char * envp[])
{
char cmd[100];
char *cmdLine;
char *expansion;
time_t now=time(NULL);
int nBytes; //size of msg rec'd
char cwd[PATH_MAX];
signal(SIGINT,ctrlCHandler);
read_history("shell.log");
add_history(ctime(&now));
fprintf(stdout,"Starting the shell at: %sn",ctime(&now));
while(true) {
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %sn", cwd);
} else {
perror("getcwd() error");
return 1;
}
cmdLine=readline("Enter a command: ");
if(!cmdLine) break;
history_expand(cmdLine,&expansion);
add_history(expansion);
if(strcasecmp(cmdLine,"bye")==0) break;
char *response=interpret(cmdLine);
fprintf(stdout,"%sn",response);
}
write_history("shell.log");
system("echo Your session history is; cat -n shell.log");
fprintf(stdout,"Server is now terminated n");
return 0;
}

More Related Content

Similar to Add a 3rd field help that contains a short help string for each of t.pdf

-- This is the shell-c Test- --shell -test sub #include -ctype-h- -- C.pdf
-- This is the shell-c Test- --shell -test sub #include -ctype-h- -- C.pdf-- This is the shell-c Test- --shell -test sub #include -ctype-h- -- C.pdf
-- This is the shell-c Test- --shell -test sub #include -ctype-h- -- C.pdf
AdrianEBJKingr
 
operating system ubuntu,linux,MacProgram will work only if you g.pdf
operating system ubuntu,linux,MacProgram will work only if you g.pdfoperating system ubuntu,linux,MacProgram will work only if you g.pdf
operating system ubuntu,linux,MacProgram will work only if you g.pdf
aptcomputerzone
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
ezonesolutions
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
Yandex
 
Network lap pgms 7th semester
Network lap pgms 7th semesterNetwork lap pgms 7th semester
Network lap pgms 7th semester
DOSONKA Group
 
operating system Linux,ubuntu,Mac#include stdio.h #include .pdf
operating system Linux,ubuntu,Mac#include stdio.h #include .pdfoperating system Linux,ubuntu,Mac#include stdio.h #include .pdf
operating system Linux,ubuntu,Mac#include stdio.h #include .pdf
aquazac
 
Unit 8
Unit 8Unit 8
Unit 8
siddr
 
Sorting programs
Sorting programsSorting programs
Sorting programs
Varun Garg
 

Similar to Add a 3rd field help that contains a short help string for each of t.pdf (20)

Railway reservation
Railway reservationRailway reservation
Railway reservation
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
String Manipulation Function and Header File Functions
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
-- This is the shell-c Test- --shell -test sub #include -ctype-h- -- C.pdf
-- This is the shell-c Test- --shell -test sub #include -ctype-h- -- C.pdf-- This is the shell-c Test- --shell -test sub #include -ctype-h- -- C.pdf
-- This is the shell-c Test- --shell -test sub #include -ctype-h- -- C.pdf
 
C program
C programC program
C program
 
operating system ubuntu,linux,MacProgram will work only if you g.pdf
operating system ubuntu,linux,MacProgram will work only if you g.pdfoperating system ubuntu,linux,MacProgram will work only if you g.pdf
operating system ubuntu,linux,MacProgram will work only if you g.pdf
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
Network lap pgms 7th semester
Network lap pgms 7th semesterNetwork lap pgms 7th semester
Network lap pgms 7th semester
 
Railwaynew
RailwaynewRailwaynew
Railwaynew
 
RAILWAY RESERWATION PROJECT PROGRAM
RAILWAY RESERWATION PROJECT PROGRAMRAILWAY RESERWATION PROJECT PROGRAM
RAILWAY RESERWATION PROJECT PROGRAM
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
 
Usp
UspUsp
Usp
 
Game unleashedjavascript
Game unleashedjavascriptGame unleashedjavascript
Game unleashedjavascript
 
operating system Linux,ubuntu,Mac#include stdio.h #include .pdf
operating system Linux,ubuntu,Mac#include stdio.h #include .pdfoperating system Linux,ubuntu,Mac#include stdio.h #include .pdf
operating system Linux,ubuntu,Mac#include stdio.h #include .pdf
 
Unit 8
Unit 8Unit 8
Unit 8
 
Sorting programs
Sorting programsSorting programs
Sorting programs
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Vcs16
Vcs16Vcs16
Vcs16
 
Ccc
CccCcc
Ccc
 

More from info245627

More from info245627 (20)

Adolescent suicides have increased in several US states during the C.pdf
Adolescent suicides have increased in several US states during the C.pdfAdolescent suicides have increased in several US states during the C.pdf
Adolescent suicides have increased in several US states during the C.pdf
 
Advanced Encryption Standard 6.4 Given the plaintext {00010203040506.pdf
Advanced Encryption Standard 6.4 Given the plaintext {00010203040506.pdfAdvanced Encryption Standard 6.4 Given the plaintext {00010203040506.pdf
Advanced Encryption Standard 6.4 Given the plaintext {00010203040506.pdf
 
Actuary and trustee reports indicate the following changes in the PB.pdf
Actuary and trustee reports indicate the following changes in the PB.pdfActuary and trustee reports indicate the following changes in the PB.pdf
Actuary and trustee reports indicate the following changes in the PB.pdf
 
Adenine is usually found in the amino form. When it undergoes an iso.pdf
Adenine is usually found in the amino form. When it undergoes an iso.pdfAdenine is usually found in the amino form. When it undergoes an iso.pdf
Adenine is usually found in the amino form. When it undergoes an iso.pdf
 
Add the function to a PyDev module named functions.py. Test it from .pdf
Add the function to a PyDev module named functions.py. Test it from .pdfAdd the function to a PyDev module named functions.py. Test it from .pdf
Add the function to a PyDev module named functions.py. Test it from .pdf
 
Add an object that flies from left to right, over and over. � The ob.pdf
Add an object that flies from left to right, over and over. � The ob.pdfAdd an object that flies from left to right, over and over. � The ob.pdf
Add an object that flies from left to right, over and over. � The ob.pdf
 
Add all steps, thank you Consider the following feedforward neural n.pdf
Add all steps, thank you Consider the following feedforward neural n.pdfAdd all steps, thank you Consider the following feedforward neural n.pdf
Add all steps, thank you Consider the following feedforward neural n.pdf
 
Action Required�The Human resources must face new challenges ever.pdf
Action Required�The Human resources must face new challenges ever.pdfAction Required�The Human resources must face new challenges ever.pdf
Action Required�The Human resources must face new challenges ever.pdf
 
Activity Compose a 5-day nutrition log for a normal week�s food int.pdf
Activity Compose a 5-day nutrition log for a normal week�s food int.pdfActivity Compose a 5-day nutrition log for a normal week�s food int.pdf
Activity Compose a 5-day nutrition log for a normal week�s food int.pdf
 
Activity 1 The role of government in promoting business ethics Disc.pdf
Activity 1 The role of government in promoting business ethics Disc.pdfActivity 1 The role of government in promoting business ethics Disc.pdf
Activity 1 The role of government in promoting business ethics Disc.pdf
 
Ace Inc. has five employees participating in its defined-benefit pen.pdf
Ace Inc. has five employees participating in its defined-benefit pen.pdfAce Inc. has five employees participating in its defined-benefit pen.pdf
Ace Inc. has five employees participating in its defined-benefit pen.pdf
 
Accrued liability for utilities. Account #1 correct Account Type cor.pdf
Accrued liability for utilities. Account #1 correct Account Type cor.pdfAccrued liability for utilities. Account #1 correct Account Type cor.pdf
Accrued liability for utilities. Account #1 correct Account Type cor.pdf
 
Accounting Elements Label each of the following accounts as an Asset.pdf
Accounting Elements Label each of the following accounts as an Asset.pdfAccounting Elements Label each of the following accounts as an Asset.pdf
Accounting Elements Label each of the following accounts as an Asset.pdf
 
Accounts in a company�s general ledger are divided into different ca.pdf
Accounts in a company�s general ledger are divided into different ca.pdfAccounts in a company�s general ledger are divided into different ca.pdf
Accounts in a company�s general ledger are divided into different ca.pdf
 
actuarial science statistics required! Let X be a truncated Poisson .pdf
actuarial science statistics required! Let X be a truncated Poisson .pdfactuarial science statistics required! Let X be a truncated Poisson .pdf
actuarial science statistics required! Let X be a truncated Poisson .pdf
 
Acuerdo y desacuerdo entre economistas Suponga que Musashi, un eco.pdf
Acuerdo y desacuerdo entre economistas Suponga que Musashi, un eco.pdfAcuerdo y desacuerdo entre economistas Suponga que Musashi, un eco.pdf
Acuerdo y desacuerdo entre economistas Suponga que Musashi, un eco.pdf
 
All of the following contributed to a surge in international lending.pdf
All of the following contributed to a surge in international lending.pdfAll of the following contributed to a surge in international lending.pdf
All of the following contributed to a surge in international lending.pdf
 
All of these statements are correct EXCEPT for which of the followin.pdf
All of these statements are correct EXCEPT for which of the followin.pdfAll of these statements are correct EXCEPT for which of the followin.pdf
All of these statements are correct EXCEPT for which of the followin.pdf
 
All of the following statements accurately describe manager�employee.pdf
All of the following statements accurately describe manager�employee.pdfAll of the following statements accurately describe manager�employee.pdf
All of the following statements accurately describe manager�employee.pdf
 
All of the following explain why spending on healthcare in the Unite.pdf
All of the following explain why spending on healthcare in the Unite.pdfAll of the following explain why spending on healthcare in the Unite.pdf
All of the following explain why spending on healthcare in the Unite.pdf
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Recently uploaded (20)

Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 

Add a 3rd field help that contains a short help string for each of t.pdf

  • 1. Add a 3rd field help that contains a short help string for each of the commands you were to implement in assignment #3. Make sure that your array(s) are big enough to handle 5 extra items beyond your initialization. To save time only include help for exercises 4, 5, 6 and 8 in this assignment, and use No help for the other entries. #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void ctrlCHandler(int signum) { fprintf(stderr,"Command server terminated using Cn"); exit(1);
  • 2. } char * fExport(char *cmd, char *tokensleft[]) { setenv(tokensleft[0],tokensleft[1],1); return "Command 'export' was received"; } char * fChdir(char *cmd,char *tokensleft[]) { int ch=chdir(tokensleft[0]); if(ch<0) perror("chdir change of directory not successfuln"); else printf("chdir change of directory successfuln"); return "Command 'chdir' was receivedn"; } char * fAccess(char *cmd,char *tokensleft[]) { int exists =0; for(int i=0;tokensleft[i]; i++) { exists =0; if(access(tokensleft[i],F_OK)==0){ exists = 1; printf("file %s existsn",tokensleft[i]); }else{ printf("file %s does not existsn",tokensleft[i]); }
  • 3. if (exists == 1){ if(access(tokensleft[i],R_OK)==0) { printf("file %s is readablen",tokensleft[i]); }else{printf("file %s is not readablen",tokensleft[i]);} if(access(tokensleft[i],W_OK)==0) { printf("file %s is writeablen",tokensleft[i]); }else{ printf("file %s is not writeablen",tokensleft[i]); } if(access(tokensleft[i],X_OK)==0) { printf("file %s is executeablen",tokensleft[i]); }else{ printf("file %s is not executeablen",tokensleft[i]); } }// exists if } //for return "Command 'acsess' was receivedn"; } char * fChmod(char *cmd,char *tokensleft[]) { unsigned int octalPerm; sscanf(tokensleft[0],"%o",&octalPerm); for(int i=1;tokensleft[i]; i++) { if(chmod(tokensleft[i],octalPerm)==0 ){ chmod(tokensleft[i],octalPerm); }else{ printf("Error: %s n",strerror(errno)); } } return "Command 'chmod' was received";
  • 4. } char * fPath(char *cmd,char *tokensleft[]) { char *pathLink; char actualPath[PATH_MAX+1]; char *pointer; char *bName; char *dName; for(int i=0;tokensleft[i]; i++) { pathLink = tokensleft[i]; pointer =realpath(pathLink,actualPath); bName = basename(actualPath); dName = dirname(tokensleft[i]); if (pointer){ printf("The Real path of %s is: %sn",tokensleft[i],actualPath); printf("The Dir name path of %s is: %sn",tokensleft[i],dName); printf("The Base name of %s is: %sn",tokensleft[i],bName); }else{ printf("Error: %s n",strerror(errno)); } } return "Command 'path' was received"; } char * fTouch(char *cmd,char *tokensleft[]) { extern int optind,optopt,opterr; struct FLAG{ bool aFlag; bool mFlag; } flags = { false, false }; int t1 = time(NULL), t2 = time(NULL); int argc = 0;
  • 5. int flag; for (int i = 0; tokensleft[i]; i++) { argc++; } while ((flag = getopt(argc, tokensleft, "m:a:")) != -1) { switch (flag) { case 'm': flags.mFlag = true; t1 = atoi(optarg); break; case 'a': flags.aFlag = true; t2 = atoi(optarg); break; case ':': if (optopt == 'm') { flags.mFlag = true; } fprintf(stderr, "%c flag is missing an argument. optopt is: %cn", flag, optopt); break; case '?': fprintf(stderr, "%c is an illegal flagn", optopt); break; } } // Print the flags and times for testing printf("Flags: -m %d -a %dn", t1, t2); printf("mFlag: %d aFlag: %dn", flags.mFlag, flags.aFlag); return "Command 'touch' was received"; } char * fLn(char *cmd,char *tokensleft[]) { int opt; int force = 0; int symbolic = 0; int argc =0;
  • 6. for (int i = 0; tokensleft[i]; i++) { argc++; } while ((opt = getopt(argc, tokensleft, "sf")) != -1) { switch (opt) { case 's': symbolic = 1; break; case 'f': force = 1; break; default: /* '?' */ fprintf(stderr, "Usage: %s [-s] [-f] file1 file2n", tokensleft[0]); } } if (argc - optind != 2) { fprintf(stderr, "Usage: %s [-s] [-f] file1 file2n", tokensleft[0]); } const char *file1 = tokensleft[optind]; const char *file2 = tokensleft[optind+1]; if (force) { remove(file2); } if (symbolic) { link(file1, file2); } else { if (link(file1, file2) != 0) { perror("Error creating hard link"); }
  • 7. } return "Command 'ln' was received"; } char * fUnset(char *cmd, char *tokensleft[]) { unsetenv(tokensleft[0]); return "Command 'unset' was received"; } char *commands[10]={"export","chdir","access","chmod", "path","touch","ln","unset"} ; char *(*methods[10])()={fExport,fChdir,fAccess,fChmod,fPath,fTouch,fLn,fUnset}; //Alternate declaration struct CMDSTRUCT { char *cmd; char *(*method)(); } cmdStruct[]={{"fred",fExport},{"mary",fChdir},{"clark",fAccess},{"sonia",fChmod},{"carlo",f Path},{"lalo",fTouch},{"samuel",fLn},{"olga",fUnset},{NULL,NULL}} ; char *interpret(char *cmdline) { char **tokens; char *cmd; int i; char *result; char sysCommand; tokens=history_tokenize(cmdline); //Split cmdline into individual words. if(!tokens) return "no response needed"; cmd=tokens[0]; //Detecting commands: table lookup: 2 techniques //Using the parallel arrays to look up function calls for(i=0;commands[i];i++)
  • 8. { if(strcasecmp(cmd,commands[i])==0) return (methods[i])(cmd,&tokens[1]); } //Using struct CMDSTRUCT as an alternative lookup method. Pick either technique, not both //Note that its possible to create multiple aliases for the same command using either method. for(i=0;cmdStruct[i].cmd;i++) if(strcasecmp(cmd,cmdStruct[i].cmd)==0) return (cmdStruct[i].method)(cmd,&tokens[1]); sysCommand=system(cmdline); if (sysCommand==-1){ return"command status: fail"; }else if (sysCommand==0){ return"command status: sucsess";} } int main(int argc, char * argv[],char * envp[]) { char cmd[100]; char *cmdLine; char *expansion; time_t now=time(NULL); int nBytes; //size of msg rec'd char cwd[PATH_MAX]; signal(SIGINT,ctrlCHandler); read_history("shell.log"); add_history(ctime(&now)); fprintf(stdout,"Starting the shell at: %sn",ctime(&now)); while(true) { if (getcwd(cwd, sizeof(cwd)) != NULL) { printf("Current working dir: %sn", cwd); } else { perror("getcwd() error"); return 1; }
  • 9. cmdLine=readline("Enter a command: "); if(!cmdLine) break; history_expand(cmdLine,&expansion); add_history(expansion); if(strcasecmp(cmdLine,"bye")==0) break; char *response=interpret(cmdLine); fprintf(stdout,"%sn",response); } write_history("shell.log"); system("echo Your session history is; cat -n shell.log"); fprintf(stdout,"Server is now terminated n"); return 0; }