如何在if语句中使用fork() [英] How to use fork() in an if statement
问题描述
有人可以向我解释fork() != 0
是什么意思吗?据我了解,我认为这意味着fork是否为假?或者,如果fork是true,那么....我不了解Fork()可以是true还是false,因为它只是创建了到父级和子级的进程的副本.另外,如果某个程序在哪里说if (Fork() == 0)
是什么意思?
Can someone please explain to me what does fork() != 0
mean? From what I understand I think it means if fork is not false? Or if fork is true then.... I don't understand how Fork() can be true or false, seeing that it just creates a copy of a process into a parent and child. Also if a program where to say if (Fork() == 0)
what would that mean?
#include "csapp.h"
int main(void)
{
int x = 3;
if (Fork() != 0)
printf("x=%d\n", ++x);
printf("x=%d\n", --x);
exit(0);
}
推荐答案
fork()
如果失败,则返回-1,如果成功,则在父级中返回派生子级的pid,在子级中返回0.因此if (fork() != 0)
测试它是否是父进程.
fork()
returns -1 if it fails, and if it succeeds, it returns the forked child's pid in the parent, and 0 in the child. So if (fork() != 0)
tests whether it's the parent process.
这篇关于如何在if语句中使用fork()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!