簡體   English   中英

Fork()和父/子進程

[英]Fork() and parent/child processes

這是關於我的作業以及老師對輸出的期望的問題。。。我對從此處輸入的代碼感到困惑。 我的輸出是數千個子進程和父進程

#include <stdio.h>
#include <unistd.h>

main()
{
/* Create three variables */
/* One to create a fork */
/* One to store a value */
/* One to use as a count control for a loop */

/* Initialize value variable here */ ;

printf("Ready to fork...\n");

/* Create fork here */

if ( /* Condition to determine if parent */ )
{
        printf( "The child executes this code.\n" );
        for (  /* Count control variable set to zero, less than five, incremented */  )
         /* Value variable */  =  /* What does value variable equal? */ ;
        printf( "Child = /* The ending value variable goes here */ " );
     }
else
    {
         for (  /* Count control variable set to zero, less than five, incremented */  )
            /* Value variable */  =  /* What does value variable equal? */ ;
        printf("Parent = /* The ending value variable goes here */ ");

    }
}

Here is the output from my program:
Ready to fork...
The parent executes this code.
Parent = 3
The child executes this code.
Child = 10

這就是我的代碼

#include <stdio.h>
#include <unistd.h>

main()
{
/* Create three variables */
int frk;
int val;
int count;

val=0;

printf("Ready to fork...\n");

frk=fork();

if ( frk==0 )
{
                printf( "The child executes this code.\n" );
                for (count=0; count<5; count++  )
                val  = frk ;
                printf( "Child = %d\n",val );
         }
else
        {
                 for (count=0; count<5; count++  )
                val  =  frk;
                printf("Parent = %d\n ",val);

        }
}

編寫的練習有點令人困惑,但是在我看來,作者的理解是:

您的程序只包含一個“值”變量:我們稱它為val

在程序調用fork() ,子進程應將val設置為10,而父進程將其設置為3。 即使它們都運行相同的代碼,名稱val指代子進程和父進程在內存中的不同位置。

換句話說,您不需要指望fork()返回3或10。在運行了一個簡短的for(...)循環之后,您只需將父進程設置為val = 3並將子進程設置為val = 10

if (frk == 0) {
    ...
    val = 10;
    printf("Child = %d\n", val);
}
else {
    ...
    val = 3;
    printf("Parent = %d\n", val);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM