SlideShare a Scribd company logo
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

DOCX
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
DOCX
Data structures
PDF
Shell to be modified#include stdlib.h #include unistd.h .pdf
PDF
c programming
PDF
Write a C++ program 1. Study the function process_text() in file.pdf
PDF
#include stdio.h#include stdlib.h#include string.h#inclu.pdf
TXT
c++ program for Railway reservation
cmdfile.txtsleep 5ls -latrsleep 3pwdsleep 1wc .docx
Data structures
Shell to be modified#include stdlib.h #include unistd.h .pdf
c programming
Write a C++ program 1. Study the function process_text() in file.pdf
#include stdio.h#include stdlib.h#include string.h#inclu.pdf
c++ program for Railway reservation

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

TXT
Railway reservation
DOCX
PDF
-- This is the shell-c Test- --shell -test sub #include -ctype-h- -- C.pdf
PDF
C program
PDF
operating system ubuntu,linux,MacProgram will work only if you g.pdf
PDF
So I am writing a CS code for a project and I keep getting cannot .pdf
PDF
Степан Кольцов — Rust — лучше, чем C++
DOCX
Network lap pgms 7th semester
TXT
Railwaynew
DOCX
RAILWAY RESERWATION PROJECT PROGRAM
PPTX
C++ Lambda and concurrency
DOCX
Game unleashedjavascript
PDF
operating system Linux,ubuntu,Mac#include stdio.h #include .pdf
PPT
Unit 8
DOC
Sorting programs
PPTX
Anti patterns
DOCX
Railway reservation
-- This is the shell-c Test- --shell -test sub #include -ctype-h- -- C.pdf
C program
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
Степан Кольцов — Rust — лучше, чем C++
Network lap pgms 7th semester
Railwaynew
RAILWAY RESERWATION PROJECT PROGRAM
C++ Lambda and concurrency
Game unleashedjavascript
operating system Linux,ubuntu,Mac#include stdio.h #include .pdf
Unit 8
Sorting programs
Anti patterns
Ad

More from info245627 (20)

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

Recently uploaded (20)

PDF
Pre independence Education in Inndia.pdf
PPTX
Lesson notes of climatology university.
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Institutional Correction lecture only . . .
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Cell Structure & Organelles in detailed.
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Classroom Observation Tools for Teachers
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
Pre independence Education in Inndia.pdf
Lesson notes of climatology university.
O7-L3 Supply Chain Operations - ICLT Program
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Sports Quiz easy sports quiz sports quiz
Institutional Correction lecture only . . .
Microbial diseases, their pathogenesis and prophylaxis
Anesthesia in Laparoscopic Surgery in India
Cell Structure & Organelles in detailed.
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
2.FourierTransform-ShortQuestionswithAnswers.pdf
Classroom Observation Tools for Teachers
Supply Chain Operations Speaking Notes -ICLT Program
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?

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; }