The code I have is here. Essentially, the custom shell needs to take echo, cd and quit as the commands and fork a child for the commands. There are no errors when it compiles but it is not running. It doesn’t echo the argument when I give, say “echo hello”…it goes into the right functions and all but I cannot pinpoint the error. I am guessing I am making a mistake with the execlp function. Can someone please help me out?
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
int main()
{
char command[256];
char * parsedCmd;
char * argument;
//char *sep[]=" ";
while (1<2)
{
printf("\nOS Assignment 1@user: ");
fgets(command, sizeof(command), stdin);
parsedCmd=strtok(command, " ");
argument=strtok(NULL, " ");
//printf("\n%s\n", argument);
if (strncmp("quit", command, 4)==0)
break;
if (strncmp("cd", parsedCmd, 2)==0)
{
printf("\nExecuting cd\n");
execCD(argument);
}
if (strncmp("echo", parsedCmd, 4)==0)
{
printf("\nEchoing now...\n");
shellEcho(argument);
}
else
printf("\nOur shell is simple. Try either cd, echo or quit :) ...\n");
}
}
int execCD(char *receive)
{
printf("\nExecuting cd as Child...\n");
printf("\nDirectory to cd is %s\n", receive);
pid_t pid;
pid=fork();
if (pid<0)
{
fprintf(stderr, "\nFork Failed\n");
return 1;
}
else if (pid==0)
{
execlp(receive, "cd", NULL);
}
else
{
wait(NULL);
printf("Child Complete");
}
return 0;
}
int shellEcho(char *receive)
{
printf("\nExecuting echo as Child...\n");
pid_t pid;
pid=fork();
if (pid<0)
{
fprintf(stderr, "\nFork Failed\n");
return 1;
}
else if (pid==0)
{
execlp(receive, "echo", NULL);
}
else
{
wait(NULL);
printf("Child Complete");
}
return 0;
}
You have the arguments to
execlpbackwards. Also, note that by convention, you need to specify “echo” twice: once as the name of the program to execute, and the second time as the 0th argument (which is usually, but not necessarily, the name of the program).Also, note that “cd” cannot be executed, as it must be implemented by the shell (it is not a separate program that can be run). It’s probably more appropriate to discuss that issue with your teacher rather than pursuing it futher here.