My code:
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
int main(){
fork();
printf("Show me the new line before the pid child dies \n");
return 0;
}
Output:
>Show me the new line before the pid child dies Show me the new line before the pid child dies"\n
>
My expected result would be to show the '\n' as part of the string and to have two separate lines, as below:
>string1 \n
>string2 \n
>
but I am getting the following:
>string1 string2 \n
>
I tried with the fflush(stdout) but didn't make a difference.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
int main(){
fork();
printf("Show me the new line before the pid child dies \n");
fflush(stdout);
return 0;
}
Same output:
>"Show me the new line before the pid child dies Show me the new line before the pid child dies"
>
How do I make it so I get the following output:
>"Show me the new line before the pid child dies \n"
> Show me the new line before the pid child dies \n"
>
Update:
If I run it as below, it shows me the correct lines (as I wanted):
Command on terminal / powershell
.\f.exe > f.out
Output:
1 Show me the new line before the pid child dies
2 Show me the new line before the pid child dies
3
I am changing my question then: Can I actually get the exact same output shown on my terminal (vs code / powershell), as I am getting on my f.out file?
I'm running MS Visual Studio on Windows.
Probably you got a racing condition, after the call to fork()
both the parent thread and the child thread are trying to print simultaneously. The behavior in this case is undefined. The whole idea of homework is probably to teach you that. You should use some sort of inter thread communication, or simply wait in the parent process (or in child it does not matter).
if (fork()) sleep(1);
Update:
After carefully reading your output line I realised that your exercise is probably to learn to wait in the parent process until the child dies, this is achieved like this:
if (fork() != 0) wait(NULL);