We know that &> outfile redirects both stdout and stderr to outfile in a UNIX shell. But how does the shell implement this? I write a naïve test:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int fd = open("tmpf", O_CREAT | O_TRUNC | O_WRONLY, 0644);
// redirect stdout to file
dup2(fd, 1);
close(fd);
// redirect stderr to stdout
dup2(2, 1);
close(2);
// print stuff to file
fprintf(stdout, "stdout string\n");
fprintf(stderr, "stderr string\n");
}
It simply redirects stdout to the file and then redirects stderr to stdout. But this doesn't work. The above code produces
$ ./a.out
stdout string
$ cat tmpf
$
If we exchange the order of stdout->file and stderr->stdout, it gives the following result
$ ./a.out
$ cat tmpf
stdout string
$