首页 文章

fork()系统调用的工作[重复]

提问于
浏览
0

这个问题在这里已有答案:

这是我的代码 - >>

#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语句“在分叉之前,x的值是10”,当它超过所有fork()系统调用时,会被打印三次 . ??请帮忙 .

1 回答

  • 1

    你应该在每个 fork() 之前调用 fflush(stdout) .

相关问题