Printf not printing immediately, although buffering is disabled - c

I'm having problem with the printf function in C. It's just not printing the output, although buffering is disabled:
setbuf(stdout, NULL);
and
setvbuf(stdout, NULL, _IONBF, 0);
also I'm using fflush(stdout);, but it still doesn't work.
This is the exact code:
int setup(){
//...
printf("Setup successful\n");
fflush(stdout);
return 0;
}
int main(int argc, char *argv[]){
setbuf(stdout, NULL);
setvbuf(stdout, NULL, _IONBF, 0);
setup();
//...
)
If the info helps; I'm on Linux (raspberry Pi).
Thanks in advance!

I’ve tried reproducing your setup as closely as possible. I therefore installed Raspbian (The Raspberry Pi operating system) in a VirtualBox image and used Geany to create, compile and execute a C file. Here is the code in its entirety:
#include <stdio.h>
int main() {
printf("Setup successful\n");
}
Save this file as test.c:
Next, click on “Build” (the brick icon):
And finally, run it (click on the paper plane icon):
As you can see, this code compiles correctly, executes, and prints the message. No explicit flushing is necessary (printf to stdout automatically flushes when encountering a newline character). This behaviour is standardised and correctly implemented by the tools installed by Raspbian so it’s reliable.

Related

How to attach stdin and stdout to the user process invoked by call_usermodehelper

After learning little bit of call_usermodehelper() and lots of trials, it executed successfully.
Here's the code:-
#include <linux/module.h>
#include <linux/umh.h>
static char *argv[] = {"/bin/sh","-c","/home/san/Temp/my_prog",0};
static char *envp[] = {"HOME=/","TERM=linux","PATH=/usr/sbin:/usr/bin:/sbin:/bin",0};
static int __init userspace_start(void) {
printk("Start...\n");
call_usermodehelper(argv[0],argv,envp,UMH_WAIT_PROC);
printk("End...\n");
return 0;
}
static void __exit userspace_exit(void) {
printk("Exit\n");
}
module_init(userspace_start);
module_exit(userspace_exit);
// my_prog.c
#include <stdio.h>
void main() {
for(int i = 0; i < 20; i++)
printf("Testing\n");
}
I'm working on Linux Kernel 4.15.0-29-generic
Now, the problem I'm facing is that I'm not getting any output on terminal. After searching I found that I need to attach stdin and stdout, also I found to override stdin and stdout. So, I got confused about 'attach/override' stdin and stdout. I'm actually noob at this and wanted to learn the stuffs about the linux kernel. So, can I get sample code about how to attach/override stdin and stdout so, that I can see output on terminal after spawning user-space program from call_usermodehelper or which steps I should follow to achieve this.
I also found call_usermodehelper_pipe but got no luck i.e when I execute:grep -r "call_usermodehelper_pipe" /usr/src/linux-headers-4.15.0-29-generic/include/linux/ I didn't got any declaration about it.
I also read that "Spawning stuff from the kernel should be only done in extremely special circumstances". But I'm doing this for learning purpose.
Thank you so much in Advance!

Where is scanf() reading input from, if not from the keyboard?

I'm a novice programmer getting introduced to C and I'm missing something fundamental about the way my scanf() works. I want to read a single int from the keyboard with code like this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int userBookSelection;
scanf("%i", &userBookSelection);
printf("Printing userBookSelection: %i", userBookSelection);
return EXIT_SUCCESS;
}
When I run the code, the console stays black until I stop debugging. There is never a cursor waiting for keyboard input. When I stop debug I can see this output in the console, same every time:
Printing userBookSelection: 2130567168
I'm debugging in Eclipse with MinGW GCC compiler on Windows. The code syntax seems to be correct -- is it possible there's something wrong in my build path to make this happen? I need to know why scanf() isn't reading for keyboard input.
So I've gotten a line of code from my professor which takes care of this bug -- whether it's a necessary solution particular to Eclipse and/or MinGW I'm not sure. In any case, here's the code with the additional line:
int main(void) {
int userBookSelection;
setvbuf (stdout, NULL, _IONBF, 0);//<---The magic line
scanf("%i", &userBookSelection);
printf("Printing userBookSelection: %i", userBookSelection);
return EXIT_SUCCESS;
}
I'd appreciate any additional wisdom on what's going on, what setvbuf() is doing and how scanf() works more fundamentally.

How to use getch() in a loop (nCurses)

This is my first time using ncurses library. So, I wanted to use getch() to get a character as it is typed by the user (without pressing return every time). However, when I run this code:
#include <pthread.h>
#include <stdio.h>
#include <curses.h>
void *userInput() {
char c;
while((c = getch()) != '~') {
printf("%c\n",c);
}
pthread_exit(NULL);
}
int main() {
cbreak();
pthread_t threads[4];
pthread_create(&threads[0], NULL, userInput, NULL);
pthread_exit(NULL);
}
It printf lots of '?'s without getting any input. Could anyone please help me understand whats wrong?
Thank you.
EDIT: removed dead code.
There are at least three problems with the program:
getch will always return an error because you did not initialize the screen with initscr or newterm. Likewise, the cbreak call does nothing except return an error.
even if you initialized the screen, calling getch with multiple threads will not work predictably because it is not thread-safe. It's an FAQ: Why does (fill in the blank) happen when I use two threads?
the printf does something, but mixing stdio (printf) and curses does not work as you'd like. Use printw for curses applications.
As for printing ?, those -1's sent to a terminal which expects UTF-8 would likely decide they're not valid UTF-8 and display the replacement character.

printf statement is not executing before scanf statement in netbean

#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,N;
for(i=0;i<5;i++)
{
printf("Enter The Number \n");
scanf("%d", &N);
printf("HELLO %d \n",N);
}
return 0;
}
When i execute the above code in the NetBeans then the output is not being executed line by line all the output is executed together i.e once when the loop end...The problem is printf and scanf are not working
Your description of the problem is actually quite good:
Many C Runtime libraries can detect whether stdout is connected to an interactive device (console window / terminal) or not.
Depending on that, the default buffering mode is selected.
Execute the program on a terminal / in a console window, and you get the standard buffering for interactive devices instead.
Alternatively, calling
setvbuf(stdout, 0, _IOLBUF, BUFSIZ);
before any other operations on that stream will set the stdout stream to default line-buffered operation.

Flushing output buffer in C (cgi)

The following code:
int z = 0;
while(z < 4)
{
printf("iteration %d\n",z);
sleep(1);
z++;
}
Works fine and stdout buffer is flushed every second if running the program from command line. However, when I try to access the program in a web browser (server - apache on linux, compiled executable (with gcc) handled through cgi), the content is displayed only after 4 seconds and not "step by step". I am looking for something like PHP's ob_flush(). And, by the way, is cgi the best way of processing compiled C executables?
Update: neither fflush(stdout) nor setvbuf(stdout, NULL, _IONBF, 0) is working!!! Works great after disabling mod_deflate.
I am not quite sure I understand your question correctly, but in C you can
Flush after each print (fflush)
Disable buffering (setbuf, setvbuf)
setvbuf(stdout, NULL, _IONBF, 0); /* this will disable buffering for stdout */
If these won't work, then either something else is doing buffering or buffering is not the problem.
You could try to fflush stdout after your printf.

Resources