where is the text printed by C printf

387 views Asked by At

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.

2

There are 2 answers

1
Throw Away Account On BEST ANSWER

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)
0
Soul Clinic On

Write in flush.c:

#include <stdio.h> 
void flush() { 
    fflush(stdout); 
}

Then:
gcc -fpic -shared flush.c -o flush.so

Then in SLIME:

(cffi:load-foreign-library "./flush.so")
(cffi:foreign-funcall "puts" :string "Hello World" :int)
(cffi:foreign-funcall "flush")

But only print in *inferior-lisp*, even with (with-output-to-string (*standard-output*...)