Matt Hintzke
Matt Hintzke

Reputation: 7984

Re-creating STDIN Redirection in C

I am trying to create a C program that redirects IO. I have output done piece of cake, but input seems to be harder. Maybe I just do not quite understand it all but I am doing something like this:

  int redFile;

  fflush(stdin);

  myio = dup(0);

  redFile = open(rhs, O_WRONLY, 0644); 

  dup2(redFile, 0);
  close(redFile);

  // Any scanf("%s", &buf) here should read from my redFile (correct?) into some buffer, buf[64] or something

   fflush(stdin);
   dup2(myio, 0);
   close(myio);

So now I have some buf[64] with a string in it from the file, redFile, but how do I make this the input to a command specified by the char * lhs (set earlier in program). My entire program uses execve() to create basically a virtual shell.

I need to be able to handle some like:

input.txt:

test1
test2
test3

tac < input.txt > output.txt

output.txt

test3
test2
test1

Upvotes: 1

Views: 127

Answers (1)

William Pursell
William Pursell

Reputation: 212158

If you want the contents of a buffer to be the input to a process, you will need to write that data into a pipe. Basically, you need to create a pipe and then fork. The child will dup its input to be read from the pipe via dup2( pfd[ 0 ], STDIN_FILENO ) and then exec, while the parent will write the data into the other side of the pipe.

Upvotes: 1

Related Questions