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.
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.