Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.4 kB
3
Indexable
Never
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[]){
 char cmd[4096];
char* buff[4096];
char* args[4096];
int d = 0;
int i = 0;

int status;
 
 while(1){
   setbuf(stdout, NULL);
   printf("Please enter command:");
   
   int n = read(0,cmd,4096);
   /*
   for(int b = 0;cmd[b]!= '\0';b++){
    if(cmd[b] == '\n'){
      cmd[b] = '\0';
    }
   }
   */
  if(cmd[n-1] == '\n'){
  cmd[n-1] = '\0';
  }

   char* token = strtok(cmd, " ");
   
   while (token) {
  
    buff[i] = token;
    
    token = strtok(NULL, " ");
    i++;
   }
   
   buff[i] = NULL;
  i = 0;
   if(strcmp(buff[0],"EXIT") == 0){
    exit(0);
   }
   if(strcmp(buff[0], "exit")== 0) {
    exit(0);
   }
   pid_t pid = fork();
   if(pid == 0){
     
    

    for (int i = 0; buff[i] != NULL; i++) {

      printf("buff[%d] = %s\n", i, buff[i]);
    }
   
    for(int z = 0; z< 3; z++)
    {
      printf("z = %d\n", z);
     
      strcpy(args[d],buff[z]);
      printf("%s", args[0]);
     
      printf("args[%d] = %s\n", d, args[d]);
      
     
        if(strcmp(buff[z],">") == 0){
             d++;
            int fdo = open( "output.txt", O_WRONLY | O_CREAT | O_TRUNC , 0777);
            int fdo2 = dup2(fdo,1);
            
           

        }
        if(strcmp(buff[z],"<") == 0){
            d++;
            int fdi = open("input.txt", O_RDONLY);
            int fd12 = dup2(fdi,0);
           
           
        }
        if(strcmp(buff[z], ">>") == 0){
            d++;
            
            int fdb = open("output.txt", O_WRONLY | O_APPEND| O_CREAT, 0777);
            int fdb2 = dup2(fdb,1);
           
        }
        
        
        d++;
        
    }
    

    printf("before execvp\n");
    
    if (execvp(args[0],args) == -1) {
      perror("execvp");
      return EXIT_FAILURE;
    }
    printf("pid in child=%d and parent=%d\n",getpid(),getppid()); 
    exit(0);
   }
   else if(pid> 0){
     wait(&status);
    if (WIFEXITED(status)) {
      printf("\n");
			printf("child exited with status = %d\n", WEXITSTATUS(status));
		}
     printf("pid in parent=%d and childid=%d\n",getpid(),pid);
    

   }
   ;
  

 


 
  
    
   
   
   


   
    
 }

}