Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C Fork()和父/子进程_C_Linux_Fork - Fatal编程技术网

C Fork()和父/子进程

C Fork()和父/子进程,c,linux,fork,C,Linux,Fork,这是关于我的家庭作业的问题,也是老师期望的输出……我不知道从这里开始该怎么做,我已经包含了我的代码。我的输出是以千为单位的子进程和父进程 #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

这是关于我的家庭作业的问题,也是老师期望的输出……我不知道从这里开始该怎么做,我已经包含了我的代码。我的输出是以千为单位的子进程和父进程

#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。在你跑了一段短距离后。。。循环,您可以将父进程设置为val=3,子进程设置为val=10


如果frk=0-有什么东西看起来不像C吗?frk==0我完全没有注意到这不是语法错误,仍然是有效的C语句,但是John已经指出了打字错误。即使在那之后,我的child和parent的值也不正确。父项以千计,子项为0。@Josamoda:frk在父项中是子项的pid,在子项中是零。您的老师可能希望您使用count来计算val,例如,孩子的val=2*count+1。
if (frk == 0) {
    ...
    val = 10;
    printf("Child = %d\n", val);
}
else {
    ...
    val = 3;
    printf("Parent = %d\n", val);
}