2013-12-16 143 views
0

這是關於我家庭作業的問題以及教師期望的輸出內容......我很困惑從哪裏開始,我已經包括了我的代碼。我的輸出都在千元子進程和父進程叉子()和父母/子女過程

#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); 

     } 
} 
+0

'if(frk = 0)' - 任何東西看起來「不像C」在那裏? – John3136

+0

frk == 0我完全錯過了 – Josamoda

+0

它不是「語法錯誤」,仍然是一個有效的C語句,但John已經指出了錯字錯誤。 –

回答

0

,因爲它是書面的練習是一種令人困惑,但在我看來,作者得到的是:

你的程序包含一個「值」變量:我們稱之爲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); 
}