【问题标题】:Fork() and parent/child processesFork() 和父/子进程
【发布时间】:2013-12-16 04:24:25
【问题描述】:

这是关于我的作业的问题,也是老师期望输出的问题……我不知道从哪里开始我已经包含了我的代码。我的输出是数千个子进程和父进程

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

        }
}

【问题讨论】:

  • if (frk=0) - 那里的任何东西看起来“不像 C”?
  • frk==0 我完全错过了
  • 它不是“语法错误”,仍然是有效的 C 语句,但 John 已经指出了拼写错误。
  • 即使在那之后,我最终得到的孩子和父母的值都不正确。父母是数千,孩子是 0。
  • @Josamoda: frk 在父级中是子级的pid,在子级中为零。您的老师可能希望您使用count 来计算val,例如,在孩子中使用val = 2*(count + 1)

标签: c linux fork


【解决方案1】:

所写的练习有点令人困惑,但在我看来,作者的意思是这样的:

您的程序包含一个“值”变量:我们称之为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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多