coutputprintfstdoutexecvp

Why am I not seeing the printf buffer flush?


I have a simple program (working example):

#include <unistd.h>
#include <stdio.h>

int main() {
  pid_t my_pid = getpid();
  char str[30];

  sprintf(str, "/proc/%d/fd", my_pid);
  printf("hello, I am gonna print out: %s", str);

  execvp( "ls", (char *[]) { "ls", str, NULL } );

  return 0;
}

compiled with gcc on a Linux VM. My question is why the output sent to printf is never printing.

I understand that printf buffers its output and only flushes on \n. I am wondering why it is that it doesn't print in this case. I read that output streams are flushed on program exit. printf is buffering outputs in a malloc'd piece of memory (I confirmed this in my implementation).

My questions about this (more details are welcome):


Solution

  • execvp replaces the old process with a new process. Any open file descriptors remain open, but the data buffered by the C stdio library is not preserved. The C startup code will attach a new FILE pointer to the STDOUT file descriptor. The key point is that a file descriptor is an OS object, whereas a FILE pointer is a C library object. Only the OS object is preserved.