【问题标题】:Working of fork() system call [duplicate]fork() 系统调用的工作[重复]
【发布时间】:2015-01-20 05:04:39
【问题描述】:

这是我的代码 -->>

#include  <stdio.h> 
#include  <stdlib.h>
#include  <sys/types.h>
#include  <sys/wait.h>
#include  <unistd.h>


int main()
{
int i ;
int x = 10 ;
int pid1, pid2, status ;

printf("Before forking, the value of x is %d\n", x);

/*
   After forking, we make the parent and its two children
       increment x in different ways to illustrate that they
   have different copies of x
*/


if ((pid1 = fork()) == 0) {

    /* First child process */
    for (i=0 ; i < 5; i++) {
       printf("\t\t\t At first child: x= %d\n", x);
       x= x+10;
       sleep(2) ; /* Sleep for 1 second */
    }
}
else {

    /* Parent process */

    /* Create another child process */
    if ((pid2 = fork()) == 0) {

        /* Second child process */
                for (i=0 ; i < 5; i++) {
                printf("\t\t\t\t\t\t At second child: x= %d\n", x);
                x= x+20;
        sleep(2) ; /* Sleep for 1 second */
                }
    }
    else {

        /* Parent process */
        for (i=0 ; i < 5; i++) {
            printf("At parent: x= %d\n", x);
            x= x+5;
            sleep(1) ; /* Sleep for 1 second */
        }

        /*
            The waitpid() system call causes the parent
            to wait for a child process with a specific pid to complete
            its execution. The input parameter can
            specify the PID of the child process for
            which it has to wait.
        */

        waitpid(pid1, &status, 0);
        waitpid(pid2, &status, 0);
    }
}
}

这个的输出就像--->

分叉前x的值为10

第二个孩子:x=10

第二个孩子:x= 30

第二个孩子:x=50

第二个孩子:x=70

第二个孩子:x= 90

分叉前x的值为10

第一个孩子:x= 10

第一个孩子:x=20

第一个孩子:x= 30

第一个孩子:x=40

第一个孩子:x=50

分叉前x的值为10

在父级:x= 10

在父级:x= 15

在父级:x= 20

在父级:x= 25

在父级:x= 30

为什么 printf 语句“在 fork 之前,x 的值是 10”在所有 fork() 系统调用之前被打印三次。 ??请帮忙。

【问题讨论】:

  • 我运行了这段代码。它只打印了一次“分叉前”行。
  • (在用sleep 替换对Sleep 的调用并至少删除* 1000 之后)

标签: c fork


【解决方案1】:

您应该在每个fork() 之前调用fflush(stdout)。

【讨论】:

  • 我想知道为什么 stdout 没有被刷新 - 至少,有问题的字符串以 \n 结尾...
猜你喜欢
  • 2011-10-03
  • 2015-02-21
  • 2014-07-25
  • 2013-08-19
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
相关资源
最近更新 更多