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.
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.