I am not sure which print function to use after fork() system call. Should I use printf(), or sprintf with write to stdout?
I was googling a lot about it. and some people say use one, some people say use another.
Any help is appreciated, thanks.
I am not sure which print function to use after fork() system call. Should I use printf(), or sprintf with write to stdout?
I was googling a lot about it. and some people say use one, some people say use another.
Any help is appreciated, thanks.
Calling fork() has no effect on anything. The world is exactly the same as it was before, you're just in a new process. I'm not sure who's telling you that you need to "print differently" after calling fork(), but whoever it is they are really, really confused.
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}
So, if printf is used concurrently, both from child and parent, interleaving will not occur?
Example of interleaving I am thinking of:
parent: printf("Hello");
child: printf("World\n");
output to console: HeWollorld
Thanks for your help
Nowhere in your question did you even hint that that was a requirement ;-)
Yes, interleaving of the output may occur -- what other possibility is there? Two programs are writing to the same device at the same time.
To prevent interleaving, the two instances of the program would have to coordinate with each other somehow (e.g. a semaphore or something like it). It's not going to happen automatically.
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}
The main issue with printf() on either side of a fork() is that standard I/O is buffered. Something like:
Could easily produce output like:Code:#include <stdio.h> #include <unistd.h> int main(void) { printf("Hello"); if(fork() == 0) { puts("child"); _exit(0); } puts("parent"); return 0; }
This is the case if "Hello" is put in the buffer but not flushed (which it probably will be since there has been no newline printed); thus the child and parent both have a buffer with "Hello", and when the flush happens, they both print it. This wouldn't be the case with write(), but you'd also be OK if you just did fflush(NULL) (this flushes all output streams; you can choose just one if that's all you're using) before the fork().Code:Helloparent Hellochild
I understand now.
Thanks for your help guys, I appreciate it.