if(fork())是否创建子进程? [英] Does if(fork()) create a child process?

查看:202
本文介绍了if(fork())是否创建子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为操作系统考试做准备,目前正试图了解此流程问题:

I'm revising for an operating systems exam and currently trying to understand this processes question:

int main() 
{
    int v=0;

    if(fork()) 
    {
        v++;

        if(!fork())
        {
            fork();
            v--; 
        }
    } 
}

所以问题要问

  1. 绘制一棵树,以反映运行上述程序时创建的进程的父子层次.

  1. Draw a tree reflecting the parent-child hierarchy of processes created when the program above is run.

已创建整数变量v的多少个单独副本?讨论程序结尾处树中每个进程的v值是什么.

How many separate copies of the integer variable v are created? Discuss what is the value of v at the end of the program for each of the processes in the tree.

我遇到的主要问题是

if(fork())

代码中的

行.通过查看其他堆栈溢出,我意识到了

line in the code. From looking at other stack overflows I realised that

if(fork()) = if(fork() != 0)

但是我仍然很难理解第一个if语句是否创建一个子进程?因为那是第二条if语句的唯一方法:

but I'm still having difficulty understanding whether the first if statement creates a child process? Because thats the only way that the second if statement:

(!fork())

可以执行吗?

这就是我目前对这个问题的理解有多远. 尝试屏幕截图

This is how far I've got with my current understanding of the question. screenshot of attempt

希望该图清晰可见!我真的很感谢有任何提示或指示.

Hopefully the diagram is legible! I'd be really grateful for any hints or pointers with this.

推荐答案

注意if (fork()) /*etc*/

pid_t newtmp = fork();
if (newtmp != 0) /*etc*/

其中,newtmp是程序中未出现的新的(新的)变量名(可以使用x1x2等...,只要在程序中未出现),和pid_t是某种整数类型(可能是int).

where newtmp is a fresh (new) variable name not occurring in your program (you could use x1, x2 etc.... provided it has no occurrence in your program), and pid_t is some integral type (probably int).

一旦为fork的结果赋予了 explicit unique 名称重新编写了代码,您会更好地理解它.

Once you rewrote your code with explicit and unique names given to result of fork you'll understand it better.

顺便说一句,代码味道很差.使用fork时,您需要处理三种情况:

BTW, the code is poor taste. When you use fork you need to handle three cases:

  • fork失败(例如,由于系统内存不足或超出某些限制),并且给出-1

  • the fork failed (e.g. because your system has not enough memory, or because you exceeded some limits) and gives -1

fork在孩子中成功完成,因此给出0

the fork succeeded in the child so gives 0

fork在父级中成功,因此给出了子级的pid.

the fork succeeded in the parent, so gives the pid of the child.

但是,当您编码if (fork())时,您会忘记-或处理不当-第一种情况(失败).它可能很少发生.

But when you code if (fork()) you are forgetting -or handling incorrectly- the first case (failure). It can rarely happen.

仔细阅读 (多次)叉子很难理解.

Read carefully (and several times) the fork(2) man page. Notice that fork is difficult to understand.

关于限制,请注意 setrlimit(2)(以及内置的ulimit bash).

Regarding limits, be aware of setrlimit(2) (and the ulimit bash builtin).

这篇关于if(fork())是否创建子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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