开发者

output of forking process

开发者_开发技巧hello every one I want to ask a question about forking

here is the code

#include  <stdio.h>
#include  <string.h>
#include  <sys/types.h>

#define   MAX_COUNT  5
#define   BUF_SIZE   100

void  main(void)
{
     pid_t  pid;
     int    i;
     char   buf[BUF_SIZE];

     fork();
     pid = getpid();
     for (i = 1; i <= MAX_COUNT; i++) {
          sprintf(buf, "This line is from pid %d, value = %d\n", pid, i);
          write(1, buf, strlen(buf));
     } 
     printf("child id :%d\n" , pid);

     printf("parent id :%d\n" , getppid());
}

and when i run it here is the output

This line is from pid 31130, value = 1
This line is from pid 31130, value = 2
This line is from pid 31130, value = 3
This line is from pid 31130, value = 4
This line is from pid 31130, value = 5
child id :31130
This line is from pid 31131, value = 1
parent id :31052
This line is from pid 31131, value = 2
This line is from pid 31131, value = 3
This line is from pid 31131, value = 4
This line is from pid 31131, value = 5
child id :31131
parent id:31130

it really confused me why

  1. the line parent id and child id printed two times

  2. why child id value is different both time when i have called for only once

  3. why the second time parent id value is equal to first one child id value

what is actually the parent and chile Id thanks alot


The function fork is called once and returns twice. So both the child and the parent do the printfs.

printf("child id :%d\n" , pid); /* Both child and parent print this. */
printf("parent id :%d\n" , getppid()); /* Both child and parent print this. */

The fact that you say "child" and "parent" doesn't really change anything so that's why you get misleading results.

A common pattern is to test the value returned by fork. It returnss 0 in the child and the PID of the child in the parent.

pid_t pid = fork();
if (pid)
    printf("I am the parent, pid: %d. The child has pid: %d\n", getpid(), pid);
else
    printf("I am the child, pid: %d\n", getpid());

/* Common code. */
for...


following is the answers of your questions:

When you create a process fork it actually starts one another process hence after forking everything is executed by the main process as well as the child process so the line parent id and child id printed twice and it given different values both the time because both are executed by different processes so both have different id and different parent id now the answer of your third question is at that time of execution the second process executing the statement so its parent is the previous process so the second time parent id value is equal to first one child id value.

I hope you would be able to understand it.


After fork call parent and child executing same code

that is the reason for getting 4 ids printed

31131 is your child process

31130 its parent

31052 is parent's parent

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜