iocommon-lispcffi

where is the text printed by C printf


I happened encounter a trouble with calling C printf function from SBCL via cffi. The problem is when I call printf function, I can't find the output text, just the return value of printf function show on the REPL. But when I quit SBCL, the output text appears on the terminal magically.

  $ sbcl
  * (ql:quickload :cffi)
  * (cffi:foreign-funcall "printf" :string "hello" :int)
  ;;=> 5
  * (quit)
  hello$ 

The last line, "hello$" means when quit from SBCL, the text "hello" appears on terminal and followed with the shell prompt "$". So where does printf print the text "hello" to?

I tried `finish-output', `force-output' on *standard-output* but that does not work.


Solution

  • The problem is that C's stdio library has its own buffering that has nothing to do with Lisp's. Flushing the output requires you to have a pointer to C's FILE *stdout variable. You can get this pointer like this:

     (cffi:defcvar ("stdout" stdout) :pointer)
    

    Then, after using printf:

    (cffi:foreign-funcall "fflush" :pointer stdout :int)