Issue
this little command :
execlp("/bin/echo", "echo", "*", ">", "toto", 0)
prints * > toto
in the terminal, but I want it to print the result of echo *
in the file toto.
The command : system("echo * > toto")
works well, but I want to use the execlp command, what I am doing wrong?
Thank you in advance.
Solution
The angle bracket ('>') redirection is shell specific.
You could do, for example:
execlp("/bin/sh", "/bin/sh", "-c", "/bin/echo * > toto", NULL);
Note that this invokes 2 specific behaviors that are shell related:
- * wildcard: the asterisk wildcard will be expanded (by the shell, very important) to all files in current directory; and
- > redirection: the stdout of the
echo
command will be redirected to file (or pipe)toto
.
If you want to do the same kind of redirection in C (i.e. without resorting to executing the shell) you must:
// open the file
int fd = open("toto", "w");
// reassign your file descriptor to stdout (file descriptor 1):
dup2(fd, 1); // this will first close file descriptor, if already open
// optionally close the original file descriptor (as it were duplicated in fd 1 and is not needed anymore):
close(fd);
// finally substitute the running image for another one:
execlp("/bin/echo", "echo", "*" 0);
Note that you'll still get '*' written to the file.
Edit: the first argument to execlp
is really the executable to run, file image that will substitute the currently running process. After this first argument comes the full argv
array, which must include argv[0]
. I've edited the code above to reflect this. Some programs use this argv[0]
to change its personality (for example, busybox
is a single executable that implements ls
, echo
, cat
and many other unix command line utilities); that surely is the case with bash
and whatever is linked from /bin/sh
.
Answered By - rslemos Answer Checked By - Candace Johnson (WPSolving Volunteer)