I have an assignment to "Create a microshell in C/C++" and I am trying to figure out what exactly that means. I have this C code so far:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <sys/utsname.h>
int main(void)
{
char buf[1024];
pid_t pid;
int status;
printf("%% ");
while (fgets(buf,1024,stdin) != NULL)
{
buf[strlen(buf) -1] =0; //remove the last character. Important!
if ((pid = fork()) <0)
printf("fork error");
else if (pid==0)
{ /* child */
execlp(buf, buf, (char *) 0);
printf("couldn't execute: %s", buf);
exit(127);
}//else if end
/* parent */
if ( (pid = waitpid(pid, &status, 0)) <0)
printf("waitpid error");
printf("%% ");
}//while end
exit(0);
}//main end
I need to be able to invoke it using just it's name. So the name of my program is prgm4.cpp, so I need to be able to do this:
%>prgm4
prgm4>(user enters command here)
What do I need to add to my code to be able to do this? Also, how would I alter this to accept a command with two words, such as cat file.txt? Thank you for any assistance.
If I understand you correctly, you're just asking how to run your program with it's name, rather than with a full path to the file.
$ prgm4 # You want this...
$ /path/to/my/program/prgm4 # ...Instead of this.
If that's the case, it doesn't have anything to do with the program itself. You need to move your program to a place that's in the $PATH
variable, like /usr/bin on Linux, or edit the PATH variable to include the directory it's already in. For example:
$ PATH="/path/to/my/program:$PATH"
See this Super User question for more details.