Unable to understand behaviour of "system" function call in C program - c

When I run the following program, the output of system("ls -l") is displayed before that of printf. Why does it happen?
#include<stdio.h>
int main()
{
printf("\nHello world");
system("ls -l"); // output of this statement is displayed before that of the preceding
// printf statement
return 0;
}
Thanks.

printf is buffered. AFAIK the buffer is written to the output only when a there is a \n or when you explicitly flush it (via fflush(3)).
So what happens is, printf writes the \n to the output, then buffers the rest of your string. Then ls -l is executed and when your program finishes the buffer is flushed automatically.

Related

Can printf write to terminal without flushing stdout?

#include <stdio.h>
int main(){
char a[2] = {0};
a[0] = 't';
printf("%s", a);
scanf("%c", a);
return 0;
}
scanf here will cause an automatic flush of stdout.
Running a.out will print t on the terminal before running scanf, more info: How is printf getting flushed before scanf is executed?
However, doing a.out > out.txt and terminating it with ^C does not print anything inside out.txt yet the output still appeared on the screen without redirecting stdout with >.
If stdout is being flushed then why out.txt is still empty?
If it's not being flushed then how did t appear on the screen in the first example?
(I know using \n or a manual fflush or properly terminating the program will fix the issue, i'm just curious about this behaviour).
The key is the word interactive:
The input and output dynamics of interactive devices shall take place as specified in 7.21.3.
As soon as you redirect the standard output to a file, it is no longer interactive.
For example the Linux C standard library actually executes the analogue of the isatty library call to figure this out. If it figures out that standard output is not directed to file it will also break this relationship. It will also increase the I/O performance of programs that work as part of a command pipeline.
You can yourself test whether stdout is connected to a terminal by executing
#include <unistd.h>
printf("stdout is connected to a terminal: %d\n", isatty(fileno(stdout)));

Weird pointer behaviour when being passed through a function [duplicate]

I'm using Anjuta and gdb on Fedora 20 and created a C Makefile project. The code looks like this:
#include <stdio.h>
int main (void)
{
° printf ("1");
° printf ("2");
° printf ("3");
return (0);
}
° means I set a breakpoint at that position.
Now when I debug the code, there's no output while the current line is one of these printf-functions. Only when I exit main '123' appears in the terminal.
If I add \n to the second printf argument, then '12' appears as output when I move from breakpoint 2 to the 3rd one.
By default, stdout is line buffered when writing to a terminal, fully buffered when writing to any other type of stream. Since you're not printing any newlines, the output is being buffered. You can change the buffering mode with setbuf(), end each string with newline, or call fflush() when you want printing to take plac.
Add fflush(stdout) after each printf. Your output is small and remains in buffer until the progam exits.
This is because printf writes to stdout which happens to be buffered. For more details see here.

unusual behaviour with printf with infinite while loop

When I run the below program, I do not get any output.
#include <stdio.h>
int main()
{
printf("hello");
while(1)
{
}
return 0;
}
whereas if i edit the printf command to add a '\n' character to the end of the string, then the expected output comes. what is going on in the first code? I simply cannot understand it.
This is because stdout is line buffered, i.e. the output is not written to the device (the terminal) until a full line has been collected.
You can call fflush(stdout); to force a flush of the buffer to the terminal. Do not try to flushing stdin by the way, that's not allowed.
try
printf("hello\n");
or
printf("hello");
fflush(stdout)
Use printf("hello\n");
For more info see answers to this question.

Why doesn't printf work when piped in Bash?

I have a Bash script work.sh that get something from STDIN and echo it to STDOUT.
I also have a C programme, return_input, that also get something from STDIN and printf to STDOUT
But when I chain them this way:
./work.sh |./return_input
printf in return_input only output to screen when exiting. Why?
Simplified:
[root# test]# cat work.sh
#!/bin/bash
for i in {1..5}
do
echo test
read
done
Output of cat return_input.c,
#include <stdio.h>
void return_input (void){
char array[30];
gets (array);
printf("%s\n", array);
printf("%#p\n", *(long *)(array+40));
}
main() {
while(1 == 1)return_input();
return 0;
}
All I/O operations are usually buffered. This is why you get the output only after you program finishes if there are not much data to overflow the buffer and output during the execution.
You can use fflush function which forces to finish I/O operation and clear buffers if you want to see output in the "real time"
You should post some code.
Try making sure that the output is flushed (using fflush(stdout); in C after you've written to it), and/or that the text contains line-feeds since typically those force the output to be flushed.
Otherwise the output might be "stuck" in a buffer, which is an optimization rather than sending single bytes across the pipeline between the processes.

Why does printf() not print anything before sleep()?

I'm just learning C with Kernighan and Ritchie's book; I'm in the basics of the fourth chapter ("Functions and Program Structure"). The other day I became curious about the sleep() function, so tried to use it like this:
#include <stdio.h>
#include <unistd.h>
int main(void)
{
printf(" I like cows.");
sleep(5);
return 0;
}
The problem is the output of the program, it looks like it does the sleep() first and then the printf(), in other words, it waits five seconds and then prints the string. So I thought, maybe the program gets to sleep() so fast that it doesn't let printf() have his work done like I want, that is print the string and then sleep.
How can I show the string and then put the program to sleep?
The compiler is GCC 3.3.5 (propolice) in OpenBSD 4.3.
printf() writes to stdout (the default output stream) which is usually line buffered. The buffer isn't flushed by the time sleep is called so nothing is displayed, when the program exits all streams are automatically flushed which is why it prints right before exiting. Printing a newline will usually cause the stream to be flushed, alternatively you could use the fflush function:
int main(void)
{
printf(" I like cows.\n");
sleep(5);
return 0;
}
or:
int main(void)
{
printf(" I like cows.");
fflush(stdout);
sleep(5);
return 0;
}
If you are printing to a stream that is not line buffered, as may be the case if stdout is redirected or you are writing to a file, simply printing a newline probably won't work. In such cases you should use fflush if you want the data written immediately.
Your problem is that printf (and anything else that uses the stdio library to write to stdout (standard output)) is buffered - line buffered if it goes to the console, and size buffered if it goes to a file. If you do a fflush(stdout); after the printf, it will do what you want. You could try just adding a newline ('\n') to your string, and that would do the right thing as long as you don't redirect standard output to a file.
I'm not 100% sure, but I think stderr isn't buffered, which can cause confusion because you might see output you made to stderr before output you previously made to stdout.
Buffering means that all the output is stored in a place (called buffer) and is output after a certain amount of data is present in it. This is done for efficiency reasons.
Some (most?) implementations clear the buffer after a newline when writing to the console, so you can also try
printf(" I like cows.\n");
instead of the call to fflush()
I implemented time encounter as following;
for (int i = 1; i <= 60; i++) {
printf("%02d", i);
fflush(stdout);
sleep(1);
printf("\b\b");
}

Resources