Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <readline/readline.h>
- #include <readline/history.h>
- #include <string.h>
- #include <unistd.h>
- #include <ctype.h>
- #include <fcntl.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <assert.h>
- #define MAXARGS 100
- #define PIPE_READ 0
- #define PIPE_WRITE 1
- typedef struct command {
- char *cmd;
- int argc;
- char *argv[MAXARGS+1];
- struct command *next;
- } COMMAND;
- char* inputfile = NULL;
- char* outputfile = NULL;
- int background_exec = 0;
- COMMAND* parse(char* linha);
- void print_parse(COMMAND* commlist);
- void execute_commands(COMMAND* commlist);
- void free_commlist(COMMAND* commlist);
- #include "parser.c"
- int main(int argc, char* argv[]) {
- char *linha;
- COMMAND *com;
- while (1) {
- if ((linha = readline("my_prompt$ ")) == NULL)
- exit(0);
- if (strlen(linha) != 0) {
- add_history(linha);
- com = parse(linha);
- if (com) {
- print_parse(com);
- execute_commands(com);
- free_commlist(com);
- }
- }
- free(linha);
- }
- }
- void print_parse(COMMAND* commlist) {
- int n, i;
- printf("---------------------------------------------------------\n");
- printf("BG: %d IN: %s OUT: %s\n", background_exec, inputfile, outputfile);
- n = 1;
- while (commlist != NULL) {
- printf("#%d: cmd '%s' argc '%d' argv[] '", n, commlist->cmd, commlist->argc);
- i = 0;
- while (commlist->argv[i] != NULL) {
- printf("%s,", commlist->argv[i]);
- i++;
- }
- printf("%s'\n", commlist->argv[i]);
- commlist = commlist->next;
- n++;
- }
- printf("---------------------------------------------------------\n");
- }
- void free_commlist(COMMAND *commlist){
- }
- void execute_commands(COMMAND *commlist) {
- int fd[2];
- pid_t pid;
- int n_pipes=2; //pipes needed
- COMMAND *aux = commlist;
- int i;
- for(i=0;i<n_pipes; i++){
- int oldfd = 0;
- if(fd[0]!=0){
- close(fd[1]);
- oldfd = fd[0];
- }
- pipe(fd);
- if((pid=fork())<0){perror("Fork Failed");}
- else
- if(pid == 0){
- if(inputfile!=NULL){
- int in = open(inputfile,O_RDONLY);
- dup2(in,STDIN_FILENO);
- inputfile = NULL;
- }
- if(outputfile != NULL){
- int out = open(outputfile, O_RDWR |O_CREAT | O_TRUNC, S_IRWXU);
- dup2(out,STDOUT_FILENO);
- outputfile = NULL;
- }
- if(oldfd)
- dup2(oldfd,STDIN_FILENO);
- if(commlist->cmd == "grepwc"){
- if(i==0){
- if(execlp("grep","grep","celio",NULL)<0){
- perror("Bad command");
- exit(1);
- }
- }
- if(i==1){
- if(execlp("wc","wc","-l",NULL) < 0){
- perror("Bad command");
- exit(1);
- }
- }
- }
- }//child
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement