这是关于我的家庭作业以及老师期望输出的问题...我很困惑从哪里开始我已经包含了我的代码。我的输出是千元的子进程和父进程
#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 :(得分:0)
编写的练习有点令人困惑,但在我看来,作者所得到的是:
您的程序包含一个“值”变量:我们称之为val
。
在程序调用{{1}}之后,子进程应将fork()
设置为10,而父进程将其设置为3.这是有效的,因为子进程和父进程具有不同的地址空间;即使它们都运行相同的代码,名称val
也会引用子进程和父进程在内存中的不同位置。
换句话说,您不需要期望val
返回3或10.运行简短的fork()
循环后,您可以将父进程设置为for(...)
并将子进程设置为val = 3
。
val = 10