I want to write a comamnd line intepreter with multiple commands per line.
I wrote a program in C which works for 1 comamnd per line but if i enter more commands dont work,comamnds are enter like: ls -l ; pwd ; cat file ; ls.
First i parse args,i put them into array and the i have this function:
pid_t pid;
pid = fork();
switch(pid) {
case -1:
printf("DEBUG:Fork Failure\n");
exit(-1);
case 0:
execvp(cmd[j], cmd);
if(execvp(cmd[j], cmd) == -1) {
printf("Command Not Found\n");
exit(0);
}
default:
wait(NULL);
printf("DEBUG:Child Finished\n");
}
My parser is :
printf("shell> ");
fgets (input, MAX_SIZE, stdin);
if ((strlen(input)>0) && (input[strlen (input) - 1] == '\n')) {
input[strlen (input) - 1] = '\0';
}
printf("INPUT: %s\n", input);
cnd = strtok(input, " ;");
int i = 0;
while(cnd != NULL) {
cmd[i] = cnd;
i++;
cnd = strtok(NULL, ";");
I think that i must use pipes to solve my problem,but how ?
Any ideas?
sorry for bad English
The way you explain it, it seems to be that you want to execute the commands one after the other, but not have them communicate with each other (besides, piping the output of ls to pwd just makes no sense).
For that the solution is simple: Split the input on the semicolon, and handle each command as it was a single command (since that's what it is).
With some pseudo-code it could look something like this
input = read_next_line();
while ((next_command = get_next_command(input)) != NULL)
{
execute_command(next_command);
}
You could implement this with e.g. strtok or similar functions.
Related
I am working on a home made shell (very simple shell). I have decided to take the route of using execvp as my path is not a changeable element for my shell. I am running into an issue with coming up with the logic on how to fork and exec multiple processes at once.
My program should work with a command as such:
ls ; echo hello ; cat shell.c
Where each ";" indicates that we would like to run these processes at once simultaneously. So on our terminal output we should get a mix of these commands working at once.
To elaborate I'd like to explain how my program works:
A. Intake full command line into char array with a grab line function
B. Split the char array received from the last function by delimiters and place into an array of char arrays (pointer to pointer).
C. If one of the elements in our array of char arrays is ";" we can assume that multi commands are necessary. This is where I have trouble.
I have gotten as far as to know exactly how many processes I need to fork and such, but I cannot seem to wrap my head around how to pass all of these functions plus their arguments to the execvp function at once. Should I use a temp array? I know this shouldn't be this complicated but for some reason I cannot figure it out. I'm submitting my launch function below, which intakes an array of char arrays and executes accordingly based on my "multiCommand" variable which is set when multi commands are needed (by my split line function)
int launch(char **args){
pid_t pid;
int status;
int i = 0;
if(strcmp(args[0], "quit") == 0){
exit(EXIT_SUCCESS);
}
if(strcmp(args[0], ";") != 0){
printf("Essential Command Found : %s\n", args[0]);
numFork++;
}
if(multiCommand == 1){
//Handle Multicommands here
printf("Multi Commands Handling Here\n");
for(; i < elements - 1; i++){
if(strcmp(args[i], ";") == 0){
if((i + 1) < elements){
printf("Essential Command Found : %s\n", args[i + 1]);
numFork++;
}
}
}
//This is where I need to figure out what to do
printf("Fork: %d times\n", numFork);
}else if (multiCommand == 0){
pid = fork();
if(pid == 0){
execvp(args[0], args);
}else{
wait(&status);
}
}
multiCommand = 0;
elements = 0;
return 1;
}
The general idea would be to have a for loop over the different commands and fork each of them.
E.g.
for(int i = 0; i < commandCount; i++) {
int pid = fork();
if(pid == 0) { //this is the child (don't forget to check for errors and what-not)
execCommand(all, of, the, info, needed);
}
}
You can easily get the different commands using strtok().
Here's an example:
#include <string.h>
#include <stdio.h>
int main() {
char input[] = "abc;def;ghi";
char *token = strtok(input, ";");
while(token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ";");
}
return 0;
}
Output:
abc
def
ghi
The final function will look something like this:
char *token = strtok(input, ";");
while(token != NULL) {
int pid = fork();
if(pid == 0) {
//token is one command
//parse the different parts here
execCommand(args, to, exec);
}
token = strtok(NULL, ";");
}
I am working on an assignment to create an extremely simple Linux shell in C, and it works almost exactly how I want it to.
If the user enters a simple Linux command, the program will run it and loop to allow another command. If the user enters "quit", the program exits.
My problem is that the commands only work the first time. Afterward, they seem to somehow become formatted improperly. Is there a way I can reinitialize my args array so that it will receive the new input properly?
int main() {
char* args[50]; // Argument array.
char userInput[200]; // User input.
char* userQuit = "quit"; // String to be compared to user input to quit program.
int pid; // Process ID for fork().
int i = 0; // Counter.
while(1) {
// Promt and get input from user.
printf("minor5> ");
fgets(userInput, sizeof(userInput), stdin);
// Pass userInput into args array.
args[0] = strtok(userInput, " \n\0");
// Loop to separate args into individual arguments, delimited by either space, newline, or NULL.
while(args[i] != NULL) {
i++;
args[i] = strtok(NULL, " \n\0");
}
// If the first argument is "quit", exit the program.
if(strcmp(args[0], userQuit) == 0) {
printf("Exiting Minor5 Shell...\n");
exit(EXIT_SUCCESS);
}
// Create child process.
pid = fork();
// Parent process will wait for child to execute.
// Child process will execute the command given in userInput.
if(pid > 0) {
// Parent //
wait( (int *) 0 );
} else {
// Child //
int errChk;
errChk = execvp(args[0], args);
if(errChk == -1) {
printf("%s: Command not found\n", userInput);
}
}
}
return 0;
}
You need to ensure that args has a NULL last value. It probably had one on the first command, by chance, but no guarantee
Here's a reworked snippet of your parsing loop [please pardon the gratuitous style cleanup]:
// Pass userInput into args array.
char *uptr = userInput;
i = 0;
while (1) {
char *token = strtok(uptr, " \n");
uptr = NULL;
if (token == NULL)
break;
args[i++] = token;
}
// NOTE: this is the key missing ingredient from your code
args[i] = NULL;
I'm trying to create a shell using C that can take multiple commands separated by a semicolon(;). Currently I'm trying to use strtok to separate the commands but I don't think I'm using it correctly. I'll post all the info I can without posting the entire code. Is strtok being used correctly?
char *semi=";";
else
{
char *token=strtok(str,semi);
if(token != NULL)
{
token=strtok(NULL,semi);
if((childpid = fork()) == 0)
{
if ((execvp(args[0], args))<0)//prints error message when unknown command is used
{
printf("Error! Command not recognized.\n");
}
execvp(args[0],args);
free(args);//deallocate args
exit(0);
}
Edit: As per instructed I removed a large chunk of the code originally posted to focus solely on the use of strtok. When compiled the makeshift shell will accept one command at a time. I'm trying to use ";" to separate and run two commands simultaneously. Am I using strtok correctly? If not, is there an alternative?
You should always check, if strtok() returns NULL. I would change the structure as follows:
char* semi = ";"; // Your semikolon
char *token = NULL; // Your token string
// ...
// Split first occour of semicolon
token = strtok(str,semi);
if(token == NULL){
perror("No command given ...");
return NULL;
}
do {
// Execute your code here
// fork() etc.
// You should get each line (each semikolon seperated string)
// and it should be stored into token
} while((token = strtok(NULL, semi) != NULL);
I hope, I did understand your problem right ...
But as I can see, you need to split the token again by spaces to get them into a char-Array for the argv[] (second parameter) of execvp(). Here the problem is, that strtok() internally uses a static (?) variable to store the last position. So using another strtok() inside the loop would "destroy" your text.
You could do something like this:
char *str; // Your string ...
char semi[1] = ";"; // Your semikolon AND space; strtok() will split at both
char *token = NULL; // Your token string
int len = 0;
char *token2;
int argvpos = 0;
// ...
// Split first occour of semicolon
token = strtok(str,semi);
if(token == NULL){
perror("No command given ...");
return EXIT_FAILURE;
}
do {
// save length of token
len = strlen(token);
// Split for blanks to get the arguments
token2 = strtok(token," ");
// Build array of arguments
while(token2 != NULL){
args[argvpos++] = token2;
token2 = strtok(NULL," ");
}
// Do something with token (as command)
// and args (as arguments)
// ...
} while((token = strtok(token+len+1, semi) != NULL);
// In the while condition you add the length to the token; so you get the "old" last position
I think it is not a good solution, but it should work. And I hope, I did understand you problem ;-)
Kind regards.
In order to work correctly, strtok should be used along with a while loop. Also, you don't need to run execvp twice.
I created a small sample program using your code to demonstrate how you can correctly use your code:
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
char str[] = "ls -1; echo 'hello world'"; // Input commands separated by ';'
// Break the commands string into an array
char *commands[10]; // Array to hold a max of 10 commands
char *semi = ";";
char *token = strtok(str, semi);
int i = 0;
while (token != NULL)
{
commands[i] = token;
++i;
token = strtok(NULL, semi);
}
int numCommands = i; // numCommands is the max number of input commands
// Run each input command in a child process
i = 0;
while (i < numCommands)
{
printf("Command: %s\n", commands[i]);
// Tokenize the command so that it can be run using execvp
char *args[10] = {}; // Array to hold command args
args[0] = strtok(commands[i], " ");
int tokenCounter = 0;
while (args[tokenCounter] != NULL)
{
tokenCounter++;
args[tokenCounter] = strtok(NULL, " ");
}
// Create a child process
int childpid = fork();
// If this is child process, run the command
if (childpid == 0)
{
if ((execvp(args[0], args)) < 0)
{
printf("Error! Command not recognized.\n");
}
exit(0);
}
// If this is the parent, wait for the child to finish
else if (childpid > 0)
{
wait(&childpid);
}
// If the child process could not be created, print an error and exit
else
{
printf("Error: Could not create a child process.\n");
exit(1);
}
++i;
}
return 0;
}
[...] Preprocesser directives
void read_command()
{
int i; //index to the arrays stored in parameter[]
char *cp; //points to the command[]
const char *hash = " "; //figures out the strings seperated by spaces
memset(command, 0, 100); //Clear the memory for array
parameter[0] = "/bn/"; //Initialize the path
//Get the user input and check if an input did occur
if(fgets(command, sizeof(command), stdin) == NULL)
{
printf("Exit!\n");
exit(0);
}
//Split the command and look store each string in parameter[]
cp = strtok(command, " "); //Get the initial string (the command)
strcat(parameter[0], cp); //Append the command after the path
for(i = 1; i < MAX_ARG; i++)
{
cp = strtok(NULL, " "); //Check for each string in the array
parameter[i] = cp; //Store the result string in an indexed off array
if(parameter[i] == NULL)
{
break;
cp = NULL;
}
}
//Exit the shell when the input is "exit"
if(strcmp(parameter[0], "exit") == 0)
{
printf("Exit!\n");
exit(0);
}
}
int main()
{
[...]
read_command();
env = NULL; //There is no environment variable
proc = fork();
if(proc == -1) //Check if forked properly
{
perror("Error");
exit(1);
}
if (proc == 0) //Child process
{
execve(parameter[0], parameter, env); //Execute the process
}
else //Parent process
{
waitpid(-1, &status, 0); //Wait for the child to be done
}
[...]
}
The basic idea of the code is to read the input command by the user (done in the read_command() function) (ex: ls -l). Then I divide the input string in little strings and store them in an array. The point is to store the command in parameter[0] (ex: ls) and the parameters in parameter[1,2,3 etc.] (ex: -l). However, I think I executing the execve() function incorrectly.
There are all types of issues with your code including the following (some of them are correctly pointed out by Jonathan Leffler):
"/bin/" is misspelled as "/bn/"
Since parameter[0] points to a string literal ("/bn/") in strcat(parameter[0], cp); you are trying to append to this string literal which is incorrect. You should allocate a buffer to hold the concatenated string instead.
Your tokenizing code doesn't handle the trailing newline in command properly.
env should point to a NULL-terminated array of strings.
In general, I think you should focus on implementing and testing parts of your code properly before integrating them in a larger program. If you tested the read_command before trying to pass its results to execve, you would notice that it doesn't work.
I am new to C and I am trying to create a simple C shell that will allow the user to perform various functions like chdir, cd, exit, mkdir.
I've posted my code below. Can anyone look through it and see what I am doing wrong? I am not sure if I am using fork and execcv correctly. Thanks!
include stdio.h
include stdlib.h
include unistd.h
include <string.h>
include sys/types.h
main() {
//char *user;
//if ((user = getlogin()) == NULL)
// perror("__getlogin1() error");
//else printf("__getlogin1() returned %s\n", user);
int j, status;
int pid, c_pid;
int i = 0;
char *tmp, **ap;
char instring[80]; // store one line of input
char *argv[10]; // store parameters in the format for execv()
promptstart:
printf("Please enter a commcand:\n");
// read a char at a time and put it in instring[]
// put a '\0' at the end
instring[i] = getc(stdin); // stdin is the keyboard
while (instring[i] != '\n') {
i++;
instring[i] = getc(stdin);
}
instring[i] = '\0'; // replace '\n' with '\0'
tmp = instring;
i = 0;
argv[i] = strsep(&tmp, " \t"); // put first word int argv[0]
while ((i < 10) && (argv[i] != '\0')) {
i++;
argv[i] = strsep(&tmp, " \t");
}
// print out the command and options.
i = 0;
while (argv[i] != '\0') {
printf("your entered: %s\n", argv[i++]);
}
//PLACE ERROR HERE
if ((c_pid = fork()) == 0) {
for (j = 0; j < 10; j++)
printf("child (%d) prints %d\n", getpid(), j);
exit(0);
} else if (c_pid > 0) {
c_pid = wait(&status);
printf("child %d exited with status %d\n", c_pid, status);
} else {
execvp(argv[0], argv);
}
goto promptstart;
}
At least IMO, you're putting far too much into main. I'd start with something like:
int main() {
char input[128];
do {
fgets(stdin, input, sizeof(input));
dispatch(input);
} while (strcmp(input, "exit"));
return 0;
}
Then dispatch will look for internal commands, and only do an exec when/if it's given a command it doesn't recognize. To keep things simple to start with, you might consider using popen to execute external commands, and leave switching to a "raw" fork/exec for later, when the limitations of popen start to cause you problems.
For shell builtins (man bash), you probably don't want to fork/exec. I would save fork/exec for running programs that are in your PATH (an environment variable that your shell will have to manage). The shell itself should interface with the filesystem through commands like chdir (man 2 chdir).
Consider using a nice string tokenizer (or just fallback to strtok) for parsing the commandline, and as another comment suggests, abstract that into a function so that your main loop is lean.