可以派生的执行顺序()来确定? [英] Can the order of execution of fork() be determined?

查看:148
本文介绍了可以派生的执行顺序()来确定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的教科书操作系统概念第七版的练习,我有点困惑如何做叉()的工作。从我的理解,叉()创建这与其父同时运行一个子进程。但随后,我们如何确切地知道哪些进程运行第一?我的意思是执行顺序。

I'm working on an exercise on the textbook "Operating System Concepts 7th Edition", and I'm a bit confused about how does fork() work. From my understanding, fork() creates a child process which runs concurrently with its parent. But then, how do we know exactly which process runs first? I meant the order of execution.

问题结果
  编写使用叉()系统调用产生的子进程Fibonacci序列中的C程序。将在命令行来提供序列的数目。

Problem
Write a C program using fork() system call that generates the Fibonacci sequence in the child process. The number of sequence will be provided in the command line.

这是我的解决方案:

#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void display_fibonacci_sequence( int n ) {
    int i = 0;
    int a = 1;
    int b = 1;
    int value;
    printf( "%d, %d, ", a, b );
    for( ;i < n - 2; ++i ) {
        value = a + b;
        printf( "%d, ", value );
        a = b;
        b = value;
    }
    printf( "\n" );
}

int main( int argc, char** argv ) {
    int n;
    pid_t pid;
    pid = fork();
    if( argc != 2 ) {
        fprintf( stderr, "Invalid arguments" );
        exit( -1 );
    }
    n = atoi( argv[1] );

    if( pid < 0 ) {
        fprintf( stderr, "Fork failed" );
        exit( -1 );
    }
    else if( pid == 0 ) {
        display_fibonacci_sequence( n );
    }
    else { // parent process
        // what do we need to do here? 
    }
}

说实话,我没有看到使用而不是使用之间的差异。再说,如果我想的的进程来处理来自用户的输入,并让的孩子的工艺处理显示,我怎么能这样做呢?

To be honest, I don't see any difference between using fork and not using fork. Besides, if I want the parent process to handle the input from user, and let the child process handle the display, how could I do that?

推荐答案

我们不知道哪个先运行,父母或子女。这就是为什么在父通常具有等待子进程完成,如果有在它们之间的执行顺序的一些相关性。

We don't know which runs first, the parent or the child. This is why the parent generally has to wait for the child process to complete if there is some dependency on order of execution between them.

在您的具体问题,没有任何特别的理由使用叉()。你的教授可能给你这只是一个简单的例子。

In your specific problem, there isn't any particular reason to use fork(). Your professor probably gave you this just for a trivial example.

如果您希望家长来处理输入和孩子来计算,你需要做的就是移动),在此您处理点以下调用叉(命令行参数。使用相同的基本逻辑上面一样,有孩子的呼叫 display_fibonacci_sequence ,并有家长只需等待

If you want the parent to handle input and the child to calculate, all you have to do is move the call to fork() below the point at which you handle the command-line args. Using the same basic logic as above, have the child call display_fibonacci_sequence, and have the parent simply wait

这篇关于可以派生的执行顺序()来确定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆