0

I am doing a minor shell implementation in c, and I am stuck.

I want to be able to redirect stdin and stdout, but I am confused. In, my shell, when I want to start a program, I use the execvp function. Now I would like to be able to redirect stdout, so If I run another process, the output should be redirected to a file instead of the screen.

Here is sample code:

pid_t pid;

// Child process
pid = vfork();

if((pid == 0)){
    freopen("myfile.txt", "w", stdout);
    char* arr[3];
    arr[0] = "cat";
    arr[1] = "someFileToCat.txt";
    arr[2] = NULL;
   execvp("cat", arr);
   fclose(stdout);
}  

It does however print in the terminal, and not in the file.

pb2q
  • 58,613
  • 19
  • 146
  • 147
user1090614
  • 2,575
  • 6
  • 22
  • 27
  • possible duplicate of [Redirecting exec output to a buffer or file](http://stackoverflow.com/questions/2605130/redirecting-exec-output-to-a-buffer-or-file) – ChrisF Sep 30 '12 at 20:30

1 Answers1

3

File streams are a C abstraction. What you are looking for are lower level system calls such as open, close, and dup2.

See Redirecting exec output to a buffer or file for a full example.

Community
  • 1
  • 1
epsalon
  • 2,294
  • 12
  • 19