KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
OS: Linux, Language: pure C I'm moving forward in learning C programming in general, and C programming under UNIX in a special case. I detected a strange (for me) behaviour of the printf() function after using a fork() call. Code #include <stdio.h> #include <system.h> int main() { int pid; printf( "Hello, my pid is %d", getpid() ); pid = fork(); if( pid == 0 ) { printf( "\nI was forked! :D" ); sleep( 3 ); } else { waitpid( pid, NULL, 0 ); printf( "\n%d was forked!", pid ); } return 0; } Output Hello, my pid is 1111 I was forked! :DHello, my pid is 1111 2222 was forked! Why did the second "Hello" string occur in the child's output? Yes, it is exactly what the parent printed when it started, with the parent's pid . But! If we place a \n character at the end of each string we get the expected output: #include <stdio.h> #include <system.h> int main() { int pid; printf( "Hello, my pid is %d\n", getpid() ); // SIC!! pid = fork(); if( pid == 0 ) { printf( "I was forked! :D" ); // removed the '\n', no matter sleep( 3 ); } else { waitpid( pid, NULL, 0 ); printf( "\n%d was forked!", pid ); } return 0; } Output : Hello, my pid is 1111 I was forked! :D 2222 was forked! Why does it happen? Is it correct behaviour, or is it a bug?
Tags (comma-separated)
Save Edits
Cancel