关于C和UNIX(MORE QUESTION)
登录 | 论坛导航 -> 华新鲜事 -> 求学狮城 | 本帖共有 7 楼,当前显示第 5 楼 : 从楼主开始阅读 : 本帖树形列表 : 返回上一页
作者:香陵居士 (等级:16 - 好恐怖呀,发帖:22662) 发表:2003-11-05 16:55:18  5楼 
Some add-ons to cigar's answer1) You just need four key points for this question: a) Fork() returns a positive PID of the child process spawned in the parent process, 0 in the child process, and negative value in parent process if it fails; b) In C, anything non-zero is considered logical true; c) && takes precedence over || in C, that is (fork() || fork() && fork()) == (fork() || (fork() && fork())); d) Logical expressions in C are short-circuited. So the program can be re-writed as: if(fork()) { printf("%d\n", getpid()); } else { if (fork()) { if (fork()) { printf("%d\n", getpid()); } } You can try to trace the program through its parent-child hierarchy, and you should be able to get the answer. 2) In general, I agree with you that it is A. But then, there is one point to note: the assignment of PID's is dependent on the underlying implementation's policy. Therefore, if one implementation choose to assign PID's the other way round, you can still get an ouput of "1." 3) You should put this question exclu (more...)
One point:
Logical expression will probably be short-circuited, depends on the platform, OS, compiler as well as optimization level set for the compiler. But for most compilers, to generate less machine code, the logical expressions are short-circuited.
最新推出专栏《倾听索罗斯》 欢迎大家前来捧场!

Yeah!
欢迎来到华新中文网,踊跃发帖是支持我们的最好方法!原文 / 传统版 / WAP版只看此人从这里展开收起列表

本帖共有 7 楼,当前显示第 5 楼,本文还有 N-1 层楼,要不你试试看:点击此处阅读更多 >>



请登录后回复:帐号   密码