Output of this fork() program [duplicate] - c

This question already has answers here:
Working of fork() in linux gcc [duplicate]
(5 answers)
Closed 10 years ago.
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
int main()
{
printf("abcd");
fork ();
printf("pqrs\n");
return 0;
}
This program gives the output as follows:
abcdpqrs
abcdpqrs
But how is it possible? Shouldn't it be:
abcdpqrs
pqrs

No
it's because fork also copies the datastructure used in printf, holding the buffer to be printed out.
If you fork the program, the buffer is not flushed.

printf does not necessarily flush stdout immediately, so what happens is that "abcd" is buffered until next output is executed. Since later both "sides" of the fork do the output, both will also flush out the "abcd".
To make it work the way you're probably guessing it would, try flushing manually;
int main()
{
printf("abcd");
fflush(stdout);
fork ();
printf("pqrs\n");
return 0;
}
$ ./a.out
abcdpqrs
pqrs

Related

Sleep function in C (POSIX) breaks my program

This is my program code:
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>
void function() {
srand(time(NULL));
while(1) {
int n = rand();
printf("%d ", n);
//sleep(1);
}
}
int main() {
pid_t pid;
pid = fork();
if (pid == 0) {
function();
}
}
With the sleep line commented out (as in the code above) the program works fine (i.e. it prints a bunch of random numbers too fast to even see if they are actually random), but if I remove the comment the program doesn't print anything and exits (not even the first time, before it gets to the sleep), even though it compiles without warnings or errors with or without the comment.
but if I remove the comment the program doesn't print anything and exits
It does not print, but it does not really exit either. It will still be running a process in the background. And that process runs your infinite while loop.
Using your code in p.c:
$ gcc p.c
$ ./a.out
$ ps -A | grep a.out
267282 pts/0 00:00:00 a.out
$ killall a.out
$ killall a.out
a.out: no process found
The problem is that printf does not really print. It only sends data to the output buffer. In order to force the output buffer to be printed, invoke fflush(stdout)
If you're not flushing, then you just rely on the behavior of the terminal you're using. It's very common for terminals to flush when you write a newline character to the output stream. That's one reason why it's preferable to use printf("data\n") instead of printf("\ndata"). See this question for more info: https://softwareengineering.stackexchange.com/q/381711/283695
I'd suspect that if you just leave your program running, it will eventually print. It makes sense that it has a finite buffer and that it flushes when it gets full. But that's just an (educated) guess, and it depends on your terminal.
it prints a bunch of random numbers too fast to even see if they are actually random
How do you see if a sequence of numbers is random? (Playing the devils advocate)
I believe you need to call fflush(3) from time to time. See also setvbuf(3) and stdio(3) and sysconf(3).
I guess that if you coded:
while(1) {
int n = rand();
printf("%d ", n);
if (n % 4 == 0)
fflush(NULL);
sleep(1);
}
The behavior of your program might be more user friendly. The buffer of stdout might have several dozens of kilobytes at least.
BTW, I could be wrong. Check by reading a recent C draft standard (perhaps n2176).
At the very least, see this C reference website then syscalls(2), fork(2) and sleep(3).
You need to call waitpid(2) or a similar function for every successful fork(2).
If on Linux, read also Advanced Linux Programming and use both strace(1) and gdb(1) to understand the behavior of your program. With GCC don't forget to compile it as gcc -Wall -Wextra -g to get all warnings and debug info.
Consider also using the Clang static analyzer.

Printf() not executing before the "while(1)" loop in C language in Linux [duplicate]

This question already has answers here:
Why does printf not flush after the call unless a newline is in the format string?
(10 answers)
Closed 5 years ago.
I noticed something strange with the following code.
int main()
{
printf("Test"); // Section 1 do something here....
while(1)
{
;
}
}
Section 1 should be executed first, then the program should get stuck in while loop.
But the result was that "Test" didn't get printed, but it got stuck in the while loop. I wonder why the code in Section 1 does not get executed?
I ran the code on Ubuntu 14.04 LTS(compiled with the default gcc compiler)
The stdout stream is buffered, therefore it will only display what's in the buffer after it reaches a newline. Add :
fflush(stdout);
after line :
printf("Test");
See also this link for other alternatives.
This must work:
#include <stdio.h>
int main() {
printf("Test");
while(1){}
}
To compile:
gcc file.c
To execute:
./a.out

What does the "exit code 10" mean in C? [duplicate]

This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 7 years ago.
I am using Sublime to program in C but when the code is compiled it keeps returning [Finished in 1.1s with exit code 10]. What does that mean? What is going on?
#include <stdio.h>
void main()
{
int x;
scanf("%d", &x);
printf("%d", x);
}
#include <stdio.h>
int main()
{
int x;
scanf("%d", &x);
printf("%d", x);
return 0;
}
main( ) does not take void as a return type.In C programming language we use int as a return type of main .Exit codes are nothing but Windows System Error Codes .I think you are using windows Operating system and for windows Operating system
exit code 10 means :The environment is incorrect.
May be your installation process was not correct .
Reinstall it and run the program .

Printf before fork() is being printed twice [duplicate]

This question already has answers here:
printf anomaly after "fork()"
(3 answers)
Closed 7 years ago.
I was writing a multi-process program using fork() and i bumped into a problem.
Below is a sample code reproducing the problem (without any sort of error checking):
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
printf("hello world");
fork();
}
This code prints 2 "hello world" statements (one from parent and the other from child). However this should not be the case since the printffunction call is prior to the fork() system call.
After testing, the problem appears to be solved by the following:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
printf("hello world\n"); \\ addition of the new line character
// or by using fflush(stdout);
fork();
}
My guessing is that the printf buffer is being copied while its not flushed, so the child process is emptying its copy of this buffer before exiting. Hence the other printf shows.
Can anyone provide a better explanation of this issue? Or even better, correct me if i am wrong or missing something.
The file handle stdout (which is used by printf) is by default line buffered, which means output using printf will be flushed (and shown in the console) either when there's a newline or when the buffer is full.
As fork creates an exact duplicate of the parent process, both processes have the same contents in the (un-flushed) output buffer, and both will be flushed when the two processes exits.
So yes you're correct in your guessing.

Why does the following program not generate any visible output?

The following C program doesn't printing anything on the screen.
I compiled the program with gcc:
#include<stdio.h>
main()
{
printf("hai");
for(;;);
}
Most likely, stdout is line buffered. Your program does not call fflush or send a newline so the buffer does not get written out.
#include <stdio.h>
int main(void) {
printf("hai\n");
for(;;)
;
return 0;
}
See also question 12.4 and What's the correct declaration of main()? in the C FAQ.
This is caused by the buffering which takes place in stdio (i.e. it is not output immediately unless you tell it to by including a \n or fflush). Please refer to Write to stdout and printf output not interleaved which explains this.
(p.s. or the compiler is not happy about the typo in #include)
Standard output tends to be line buffered by default so the reason you're not seeing anything is because you haven't flushed the line.
This will work:
#include <stdio.h>
int main (int argC, char *argV[])
{
printf("hai\n");
for(;;)
;
return 0;
}
Alternatively, you could fflush standard out or just get rid of the infinite loop so the program exits:
#include <stdio.h>
int main (int argC, char *argV[])
{
printf("hai");
return 0;
}
but you probably want the newline there anyway.
Your for(;;) loop stops the stream from being flushed. As others have suggested, add a newline to the string being output, or flush the stream explicitly:
fflush( stdout );
after your printf. And correct the spelling of #include.

Resources