gpt4 book ai didi

fork()的执行顺序可以确定吗?

转载 作者:太空狗 更新时间:2023-10-29 16:35:13 25 4
gpt4 key购买 nike

我正在做教科书“操作系统概念第 7 版”的练习,我对 fork() 的工作原理有点困惑。根据我的理解,fork() 创建了一个与其父进程同时运行的子进程。但是,我们如何确切地知道哪个进程先运行呢?我的意思是执行顺序。

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?
}
}

老实说,我看不出使用 fork 和不使用 fork 有什么区别。另外,如果我想让parent进程处理用户的输入,让child进程处理显示,我该怎么做呢?

最佳答案

你问了很多问题,我会尽量按方便的顺序回答。

第一个问题

To be honest, I don't see any difference between using fork and not using fork.

那是因为这个例子不是很好。在您的示例中,父项不执行任何操作,因此 fork 没有用。

第二

else {
// what do we need to do here?
}

您需要wait(2)让 child 终止。请务必仔细阅读该页面。

第三

I want the parent process to handle the input from user, and let the child process handle the display

读取fork前的输入并“处理”里面的显示if (pid == 0)

第四个

But then, how do we know exactly which process runs first?

很少有程序应该关注这一点。你无法知道执行顺序,它完全取决于环境。 TLPI 是这样说的:

After a fork(), it is indeterminate which process—the parent or the child—next has access to the CPU. On a multiprocessor system, they may both simultaneously get access to a CPU.

Applications that implicitly or explicitly rely on a particular sequence of execution in order to achieve correct results are open to failure due to race conditions

也就是说,操作系统可以让您控制此顺序。例如,Linux 有 /proc/sys/kernel/sched_child_runs_first

关于fork()的执行顺序可以确定吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6696959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com