Sabemos que &> outfile redirige tanto stdout como stderr a outfile en un shell UNIX. Pero, ¿cómo implementa esto el shell? Escribo una prueba ingenua:
#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"); } Simplemente redirige stdout al archivo y luego redirige stderr a stdout . Pero esto no funciona. El código anterior produce
$ ./a.out stdout string $ cat tmpf $ Si intercambiamos el orden de stdout->file y stderr->stdout , da el siguiente resultado
$ ./a.out $ cat tmpf stdout string $No cierre sus FD de destino. El único FD que debe cerrar es el controlador de tmpf ; tanto stdout como stderr deben estar abiertos para poder escribir en ellos.
Además, debe ser dup2(1,2) para copiar stdout a stderr -- hacer frente a stderr a stdout (como lo hace el código original) descarta su identificador en tmpf .
#include <stdio.h> #include <unistd.h> #include <fcntl.h> int main() { int fd = open("tmpf", O_CREAT | O_TRUNC | O_WRONLY, 0644); // copy FD to stdout ("redirect stdout to fd") dup2(fd, 1); // fd was copied to stdout so we don't need the original close(fd); // copy stdout fd to stderr ("redirect stdout to stderr") dup2(1, 2); // print stuff to file fprintf(stdout, "stdout string\n"); fprintf(stderr, "stderr string\n"); } También vea esto ejecutándose en un entorno limitado en línea enhttps://replit.com/@CharlesDuffy2/KnowingWobblyFibonacci#main.c (puede usar "Mostrar archivos" para ver el archivo tmpf resultante en la salida).