Home > Net >  How can the multi-core cpu run the program interleaved?
How can the multi-core cpu run the program interleaved?

Time:02-15

The output of the program are not obviously contents from the printf()s in teh code. Instead it looks like characters in irregular sequence. I know the reason is because the parent process and child process are running at the same time, but in this program I only see pid=fork(), which I think means pid is only the id of child process.
So why can the parent process print?
How do the two processes run together?

// fork.c: create a new process

#include "kernel/types.h"
#include "user/user.h"

int
main()
{
  int pid;

  pid = fork();

  printf("fork() returned %d\n", pid);

  if(pid == 0){
    printf("child\n");
  } else {
    printf("parent\n");
  }
  
  exit(0);
}

output:

ffoorrkk(())  rreettuurrnende d 0
    
1c9h

ilpda

rent

CodePudding user response:

I focus my answer on showing how the observed output can result from the shown program. I think that it will already clear things up for you.

This is your output.
I edited it to use a good guess of what is parent (p) and child (c):

ffoorrkk(())  rreettuurrnende d 0\n 
cpcpcpcpcpcpcpcpcpcpcpcpccpcpcppccc

1 c9h\n 
pccpcpp
  
ilpda\n  
ccpcpcc

rent
pppp

If you only use the chars with a "c" beneath, you get

fork() returned 0
child

If you only use the chars with a "p" beneath, you get

fork() returned 19
parent

Split that way, it should match what you know about how fork() works.

Comments already provided the actual answer to the three "?"-adorned questions in title and body of your question post.

Lundin:

It creates two processes and they are executed just as any other process, decided by the OS scheduler.

Yourself:

each time fork() is called it will return twice, the parent process will return the id of child process, and child process will return 0

Maybe for putting a more obvious point on it:
The parent process receives the child ID and also continues executing the program after the fork().
That is why the output occurs twice, similarily, interleaved, with differences in PID value and the selected if branch.

Relevant is also that in the given situation there is no line buffering. Otherwise there would be no character-by-character interleaving and everthing would be much more readable.

  • Related