-1
#include <unistd.h>
#include <sys/types.h> 
#include <sys/wait.h>
#include <stdlib.h>
#include <fcntl.h> // open
#include <stdio.h>

int main() {
  close(1); // close standard out
  open("log.txt", O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
  puts("Captain's log");
  chdir("/usr/include");
  execl("/bin/ls", "ls", ".", (char *)NULL); 
  perror("exec failed");
  return 0;
}

When I check log.txt, I could not find "Captain's log". I supposed it runs before execl, thus it should be there!

kww
  • 1
  • 3

1 Answers1

0

You are writing it to the standard output, why would you expect it to be in the file?

If you want to redirect stdout just use freopen()

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include <unistd.h>

int main()
{
    FILE *file;

    file = freopen("log.txt", "w", stdout);
    if (file == NULL)
        return -1;

    printf("Captain's log");
    chdir("/usr/include");

    if (execl("/bin/ls", "ls", ".", NULL) != 0)
        perror("exec failed");
    fclose(file);

    return 0;
}
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Hi I ran your code but still could not find "Capitain log" in the log.txt. Did you run your code? As I closed the stand output, I think it should go to log.txt. That's also where the output of execl going to. I want to know whether it does not work as I thought. – kww Feb 23 '15 at 04:22
  • I think @immibis is right. Your code also works if you add 'fflush(stdout);' after 'printf("Captain's log");' – kww Feb 23 '15 at 04:28
  • @kww so just `printf("Captain's log\n")`? And my code works because of `fclose()`, since `fclose()` also flushes the buffers. – Iharob Al Asimi Feb 23 '15 at 10:38
  • I tested your code and it did not work if you don't add 'fflush(stdout);' after 'printf("Captain's log");' – kww Feb 23 '15 at 16:52
  • @kww it worked in my case, why would that be...??? I thought that `fclose()` would flush the buffer. – Iharob Al Asimi Feb 23 '15 at 23:38