Saturday, March 7, 2015

Handling input-output redirection for Linux commands in C++

Opening the file and duplicating the file descriptor for input.

Throws errno if either of those operations failed.
Retuns the file descriptor.
int startRedirectIn(const char *file){
  int in;
  in=open(file,O_RDONLY);
  if(in<0){
    throw errno;
  }
  int dup=dup2(in,0);
  if(dup<0){
    close(in);
    throw errno;
  }
  return in;
}

Opening/creating the file and duplicating the file descriptor for output.

Throws errno if either of those operations failed.
append is used to distinguish between ">" and ">>"
Retuns the file descriptor.

int startRedirectOut(const char *file,bool append){
  int out;
  if(append){
    out=open(file,O_WRONLY | O_CREAT | O_APPEND);
  }else{
    out=open(file,O_WRONLY | O_CREAT);
  }
  if(out<0){
    throw errno;
  }
  int dup=dup2(out,1);
  if(dup<0){
    close(out);
    throw errno;
  }
  return out;
}

Closing a file descriptor/stopping the redirection.

void stopRedirect(int rdr){
  if(rdr!=-1){
    close(rdr);
  }
}


This is part of the LinuxShell project.

No comments: