一个关于linux fork()的笔考题
一个关于linux fork()的笔试题
14 If one compiled and ran the following C Program in linux. Which of the descriptions below is(are) correct, assuming that the fork() syscall will not fail?
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int i = 1;
if(!fork()) i++;
printf("%d\n", i);
if(!fork()) i++;
printf("%d\n", i);
return 0;
}
A. The output will include number "1" exactly two times;
B. The output will include number "2" exactly two times;
C. Number "3" will always be last outputted;
D. Number "1" will always be ahead of number "3" in output;
E. It is possible that no number "3" in output, because "i++" is not an atomic operation.
------解决方案--------------------
sleep(10), 等待十秒啊,这几乎可以100%保证在getppid执行的时候,4个进程都还没有退出。
所以ppid就不易等于1啊。
14 If one compiled and ran the following C Program in linux. Which of the descriptions below is(are) correct, assuming that the fork() syscall will not fail?
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int i = 1;
if(!fork()) i++;
printf("%d\n", i);
if(!fork()) i++;
printf("%d\n", i);
return 0;
}
A. The output will include number "1" exactly two times;
B. The output will include number "2" exactly two times;
C. Number "3" will always be last outputted;
D. Number "1" will always be ahead of number "3" in output;
E. It is possible that no number "3" in output, because "i++" is not an atomic operation.
linux fork
------解决方案--------------------
sleep(10), 等待十秒啊,这几乎可以100%保证在getppid执行的时候,4个进程都还没有退出。
所以ppid就不易等于1啊。