Reputation: 893
My code so far handles the ls
command when the user types it. I want to be able to handle commands like ls -l /tmp
.
My code so far.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <sys/types.h>
int main(void)
{
for(;;){
char str[500];
printf("Type a command : \n");
scanf("%s",str);
char *path;
path = getenv("PATH");
char *argv[] = { path ,NULL};
int status;
int pid = fork();
if ( pid == 0 ) {
printf("executing==============> %s \n",str);
execvp(str,argv);
}
wait(&status);
}
}
Any ideas? I have to do it without system()
.
Upvotes: 1
Views: 126
Reputation: 893
This worked for me:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <sys/types.h>
#define MAX_NAME_SZ 256
int main(void)
{
char *str,*ret, *pa1, *pa2, *dtm ,*pa3;
str=(char *)malloc(50*sizeof(char));
ret=(char *)malloc(50*sizeof(char));
pa1=(char *)malloc(50*sizeof(char));
pa2=(char *)malloc(50*sizeof(char));
dtm=(char *)malloc(50*sizeof(char));
pa3=(char *)malloc(50*sizeof(char));
char ch =' ' ;
printf("Type a command : \n");
fgets (str, MAX_NAME_SZ, stdin);
if ((strlen(str)>0) && (str[strlen (str) - 1] == '\n'))
str[strlen (str) - 1] = '\0';
ret = strchr(str, ch);
if (ret !=NULL)
{
strcpy( dtm, str );
sscanf( dtm, "%s %s %s ", pa1, pa2,pa3 );
}
char *path;
path = getenv("PATH");
int status=2;
int pid = fork();
if ( pid == 0 ) {
if (ret !=NULL){
char *argv[] = { path ,pa2, pa3 ,NULL};
execvp(pa1,argv);
}
else {
char *argv[] = { path ,NULL};
execvp(str,argv);
}
}
wait(&status);
}
Upvotes: 0
Reputation: 321
Use "system" function for the same. system(str) should probably work. This function creates a separate thread, executes the command provided to it. See 'man system' for details of it.
Upvotes: 0
Reputation: 3405
You can do this and comparable things easily with system(str)
.
It forks, calls execl("/bin/sh", "sh". "-c", command, (char *) 0);
and returns after the command has completed.
As it calls the shell, it support also the shell built-ins.
Upvotes: 1
Reputation: 526
The execvp
system call expect as its parameters a string with the command and an array of strings starting with the command, followed by its parameters, one by one, and ending with a NULL string.
In your case, it would be:
char *argv[] = {"ls", "-l", "/tmp", NULL};
Remember that this piece of code is just an illustration of what is behind the scenes. You need to construct argv[]
based on the user's input.
You can combine strchr()
to tokenize your input (looking for blank spaces) and then using sscanf
to read one part of the string. Then you have to update the input pointer to the value returned by strchr()
+ 1 and use sscanf()
to read the next part of the command.
Upvotes: 2