'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 1:[1]
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)
Solution 2:[2]
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*...)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Throw Away Account |
| Solution 2 | Soul Clinic |
