2013-12-16 148 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); 
}