关于C和UNIX(MORE QUESTION)
登录 | 论坛导航 -> 华新鲜事 -> 求学狮城 | 本帖共有 7 楼,当前显示第 3 楼 : 从楼主开始阅读 : 本帖树形列表 : 返回上一页
作者:Flying (等级:18 - 华新水车,发帖:16849) 发表:2003-11-05 11:10:17  3楼  评分: 
Some add-ons to cigar's answer
1)
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 exclusively to hash here instead... (just joking :^)

“Hash”直译为“哈希”,不过是一个无用的音译。

“Hash”用于名词,通常为“hash函数”或“hash算法”(“Hash函数”只不过是“hash算法”的数学表述)。hash是指一类单向函数,在计算机科学领域中多用于数据认证。hash的不可逆性保证了即使公开基于某个输入的函数值,也没有好方法可以还原并找出原来的输入值。

“Hash”用于动词,可译为“散列”或“混杂”。这是基于“hash”一词的英文原意的。在计算机科学中多指通过对一系列输入进行运算,而把它们分散到不同的集合里面去。

4)
Indeed, you can do the following and verify it yourself:
cd /
ls -ld . ..

You shall see that both . and .. for the directory / are pointing to the same inode.
Flying @way 吳穎暉
欢迎来到华新中文网,踊跃发帖是支持我们的最好方法!原文 / 传统版 / WAP版只看此人从这里展开收起列表

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



请登录后回复:帐号   密码