C编程中的Fork()函数 [英] Fork() function in C programming

查看:98
本文介绍了C编程中的Fork()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要了解以下说明:

I just need to understand this statement:

if (fork() && !fork())

这不总是错误的吗?我的意思是,如果我写:

shouldn't it always be false? I mean, if I write:

if (a && !a)

它总是错误的,所以第一个也应该总是错误的,我错了吗?当然可以,但是我希望有人可以向我解释这个奇怪的事情.

It's always false so the first should always be false too, am I wrong? Of course I am, but I'm hoping someone can explain this strange thing to me.

我正在为考试而学习C,我必须解析此代码:

I'm studying C for an exam and I had to resolve this code:

int main(){
if(fork && !fork()){
   printf("a\n");
}
else printf("b\n");
}

推荐答案

对Unix进程创建系统的每个调用都将调用fork()返回两次.首先,它将子代的PID返回给父代(该过程称为fork()).其次,它对新创建的孩子返回0.

Every calls to the unix process creation system call fork() returns twice. First it returns with the PID of the child to the parent(the process which called fork()). Second it returns to 0 to the newly created child.

摘自手册页:

返回值

成功后,将在父级中返回子进程的PID,并在子级中返回0.失败时,将在父级中返回-1,不创建任何子级进程,并正确设置errno.

以您的情况

if (fork() && !fork())

if中的语句调用两次fork.所以会发生以下情况:

The statement inside if , calls fork twice. So what will happen is following :

A
|----------------B
|                |
|---C            |
|   |            |         

现在第一次调用fork()将同时在A和B中返回.在A中它将为非零,在B中将为零.

Now first call to fork() will return in both A and B. In A it will be nonzero and in B it will be zero.

仅会从A引发对fork()的第二次调用.因为第一个fork返回0到B,它将不会调用第二个fork(). 这是因为&&如果发现第一个操作数不为零,则会使求值短路.感谢Daniel指出了这一点.

Second call to fork() will be evoked only from A. because first fork returned 0 to B, it will not Evoke a second fork(). its because && short circuits the evaluation if first operand is found non zero. Thanks to Daniel for pointing this out.

因此,我们可以根据此表:

So we can make a table out of this:

PID       fork()1      fork()2
------------------------------
A           >0          >0
B           =0          >0
C           >0          =0

因此,从图表中,进程C的if将被评估为 TRUE

So from the chart, Process C's if will be evaluated to TRUE

请记住,fork()1没有返回C,这一点很重要.它从其父级获得了已评估表达式的副本.

Its important to remember, fork()1 didn't returned to C . it got the copy of Already evaluated expression from its parent.

我希望这能解释您的问题.

I hope this explains your question.

这篇关于C编程中的Fork()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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