im learning about fork()
but something is working wrong in my ubuntu. im running this code:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
printf("--beginning of program\n");
int counter = 0;
pid_t pid = fork();
if (pid == 0)
{
// child process
int i = 0;
for (; i < 5; ++i)
{
printf("child process: counter=%d\n", ++counter);
}
}
else if (pid > 0)
{
// parent process
int j = 0;
for (; j < 5; ++j)
{
printf("parent process: counter=%d\n", ++counter);
}
}
else
{
// fork failed
printf("fork() failed!\n");
return 1;
}
printf("--end of program--\n");
return 0;
}
i know the parent and the child should run their code in no specific order so the code should return something like this:
-beginning of program
parent process: counter=1
parent process: counter=2
parent process: counter=3
child process: counter=1
parent process: counter=4
child process: counter=2
parent process: counter=5
child process: counter=3
child process: counter=4
child process: counter=5
--end of program--
But every time i run the program, they run in what it seems to be the same order. here is a capture of what i get every single time i run this program:
user@user-VirtualBox:~/Documents/S-O$ ./sample
--beginning of program
parent process: counter=1
parent process: counter=2
parent process: counter=3
parent process: counter=4
parent process: counter=5
--end of program--
user@user-VirtualBox:~/Documents/S-O$
child process: counter=1
child process: counter=2
child process: counter=3
child process: counter=4
child process: counter=5
--end of program--
it seems like the parent finish first, and then the child starts. but i guess thats not true. please note that the second shell prompt is opened by the program itself. any ideas of what may be happening?
Edit:
if i put an sleep(1)
it works just fine. i still think that with no delay it shouldn't always have the same execution order. even counting until 100, it giver the same thing