As shown below, I want to redirect stderr from execvpe() to file. But the resulted /tmp/test does not contain expected content.
// redirect.cpp
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
int fd = open("/tmp/test", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd != -1) {
dup2(fd, 1);
dup2(fd, 2);
close(fd);
}
char* argv[] = {"ls-not-exist","-al","/etc/passwd",(char*)0};
char* envp[] = {"PATH=/bin", 0};
int ret = execvpe(argv[0],argv,envp);
printf("ret:%d %d\n", ret, errno);
return 0;
}
My expected output is like
$ ls-not-exist -al /etc/passwd
ls-not-exist: command not found
But the actual output is
$ ./redirect; cat /tmp/test
ret:-1 2
which does not contain stderr content.
I also tried with other function(execvp()) in exec() family, but also failed.