Redirecting inside execvp () call does not work

I ran a small program that executes a given command using execvp (). It works fine when redirection is not used, but when I run the command, for example:

cat file1.txt > redirected.txt 

cat displays the following error messages and failure:

 cat: >: No such file or directory cat: redirected.txt: No such file or directory 

I did a bit of work, and I'm starting to think that maybe execvp () cannot do the redirection because it does not start in the shell. Does this mean that I will have to manually select when the redirection happens and use pipes in my fork / exec code to get around this limitation? Is there a better way than using execvp ()?

Thanks!

+3
source share
3 answers

Your “small program executing a given command” is essentially a shell. Since you are writing a shell, your job is to implement a redirect with whatever syntax you want. The redirection operator > not a feature of the kernel; it is a shell function.

To implement sh style redirection, you must parse the command, find the redirection operators, open the files, and assign them to I / O descriptors. This must be done before execvp called. Find the dup2 system call.

+7
source

You can use system () if you really want to use such syntax. As you noted, redirection and expansion of wildcards and a whole bunch of other things are handled by the shell on Unix-like systems.

The way to do this with fork is something like this:

 int kidpid; int fd = open("redirected.txt", O_WRONLY|O_TRUNC|O_CREAT, 0644); if (fd < 0) { perror("open"); abort(); } switch (kidpid = fork()) { case -1: perror("fork"); abort(); case 0: if (dup2(fd, 1) < 0) { perror("dup2"); abort(); } close(fd); execvp(cmd, args); perror("execvp"); abort(); default: close(fd); /* do whatever the parent wants to do. */ } 
+4
source

It seems to be easiest to do the following:

 execlp( "/bin/sh", "/bin/sh", "-c", "cat file1.txt > redirected.txt", (char *)NULL ); 

You can do the same with execvp .

+3
source

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


All Articles