KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am writing a small linux shell in C and am so very close to being done. I take in a command from the user and store it in args , delimited by spaces. In the following example, let's say that args contains the following: args[] = {"ls", "-l", "|", "wc"}; My function takes in args and also takes in how many pipes there are. I've commented my code as much as possible. Here it is: int do_command(char **args, int pipes) { // The number of commands to run const int commands = pipes + 1; int i = 0; int pipefds[2*pipes]; for(i = 0; i < pipes; i++){ if(pipe(pipefds + i*2) < 0) { perror("Couldn't Pipe"); exit(EXIT_FAILURE); } } int pid; int status; int j = 0; int k = 0; int s = 1; int place; int commandStarts[10]; commandStarts[0] = 0; // This loop sets all of the pipes to NULL // And creates an array of where the next // Command starts while (args[k] != NULL){ if(!strcmp(args[k], "|")){ args[k] = NULL; // printf("args[%d] is now NULL", k); commandStarts[s] = k+1; s++; } k++; } for (i = 0; i < commands; ++i) { // place is where in args the program should // start running when it gets to the execution // command place = commandStarts[i]; pid = fork(); if(pid == 0) { //if not last command if(i < pipes){ if(dup2(pipefds[j + 1], 1) < 0){ perror("dup2"); exit(EXIT_FAILURE); } } //if not first command&& j!= 2*pipes if(j != 0 ){ if(dup2(pipefds[j-2], 0) < 0){ perror("dup2"); exit(EXIT_FAILURE); }
Tags (comma-separated)
Save Edits
Cancel