Redirecting output to a file in C

i encoded the base shell in C to execute basic commands, it will execute the commands ls , ls -al , ls -al | more ls -al | more etc.

I want to execute the following command in my shell. eg;

 ls -al > a.txt 

this will give me a.txt file containing the output of the ls -al process. I found one solution, changing the command in my shell, for example [command1] | tee [filename] [command1] | tee [filename] . in this case, it will change ls -al > a.txt to ls -al | tee a.txt ls -al | tee a.txt . but this process also gives output to the file and terminal. how to stop printing output in the terminal.

or is there a better solution than using the tee command. thanks in advance...

+6
source share
3 answers

This is the result of my testing with dup2

The thinner dot remembers fflush at the right time :) Otherwise, you will get very amazing results.

Also prefer fileno over hardcoding 1 (stdout) 2 (stderr).

Redirecting stdin left as an exercise for the reader

 #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> int main(int argc, const char *argv[]) { int out = open("cout.log", O_RDWR|O_CREAT|O_APPEND, 0600); if (-1 == out) { perror("opening cout.log"); return 255; } int err = open("cerr.log", O_RDWR|O_CREAT|O_APPEND, 0600); if (-1 == err) { perror("opening cerr.log"); return 255; } int save_out = dup(fileno(stdout)); int save_err = dup(fileno(stderr)); if (-1 == dup2(out, fileno(stdout))) { perror("cannot redirect stdout"); return 255; } if (-1 == dup2(err, fileno(stderr))) { perror("cannot redirect stderr"); return 255; } puts("doing an ls or something now"); fflush(stdout); close(out); fflush(stderr); close(err); dup2(save_out, fileno(stdout)); dup2(save_err, fileno(stderr)); close(save_out); close(save_err); puts("back to normal output"); return 0; } 
+10
source

Do not use the channel when the output should go to the file.

When you force your child to run the ls , you mark the redirection and open the file; you then use dup2() (or close() and dup() ) to make the file descriptor now standard for the child; you close the duplicate file descriptor - the one returned by open() ; then you execute ls as usual; its standard output is now sent to a file.

Please note that you are redirecting I / O without pipes after forking, not earlier. Pipes must be configured before forking, but there is no other I / O redirection.

+3
source

Before you call execve(2) in a newly created process to execute a command, you can redirect your standard input or output using the dup2(2) system call:

 /* redirect stdout to a file */ dup2(1, some_open_file_descriptor); 

Of course you need to have some error handling.

+2
source

Source: https://habr.com/ru/post/903819/


All Articles