[英]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.