一个小型 C 程序的结果
我们需要告诉以下 C 程序的结果:
main()
{
int pid, k, som;
som = 0; k = 2;
pid = fork();
if(pid == 0)
k=5;
else
wait(0);
for(int i = 1; i <= k; i++)
som += i;
printf("%d", som);
}
我的第一个期望是 3。当进行 fork 调用时,进程的内存被复制,并且两个程序都开始运行。 然后子进程执行,但是k仍然等于2。所以最后,它执行1 + 2 = 3;
但是当这个程序执行时,它输出 153。我还没有得到最接近的线索为什么它输出这个。
谁能告诉我为什么吗?
We need to tell the outcome of the following C program:
main()
{
int pid, k, som;
som = 0; k = 2;
pid = fork();
if(pid == 0)
k=5;
else
wait(0);
for(int i = 1; i <= k; i++)
som += i;
printf("%d", som);
}
My first expectation is 3. When a the fork call is made, the memory of the process is copied, and both programs go running. The child process then executes, but k still equals 2. So at the end, it executes 1 + 2 = 3;
But when this program is executed, it outputs 153. I haven't got the nearest clue why it outputs that.
Can anyone tell why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
原因是你有两个进程打印到同一个控制台。 “fork”是一个 unix/linux 命令,调用一次并返回两次。 其中一个返回值将位于调用 fork 的原始进程中,并将返回所生成的子进程的 PID。 第二个返回值为 0,这表明它是子进程。
其中一个程序,我相信是孩子,首先执行并计算 15 作为值,最后将其打印到控制台。 由于 wait(0),父程序第二次执行并生成值 3。
The reason why is you have 2 processes printing out to the same console. "fork" is a unix/linux command that is called once and returns twice. One of the returns will be in the original process which called fork and will return the PID of the child process that was spawned. The second return will be 0 and this indicates it is the child process.
One of the programs, the child i believe, executes first and calculates 15 as the value and prints it to the console last. The parent program executes second because of the wait(0) and produces the value 3.
15
由子级打印,3
由父级打印。15
is printed by child, and3
by parent.A 是父级,B 是子级,以下是重要的几行:
A is parent, B is the child, here are the important lines:
值之间没有打印换行符,因此父母的答案会出现在孩子的答案之后。
贾里德关于这些价值观的原因是正确的。
There's no newline being printed between the values so the parent's answer appears right after the child's answer.
Jared's correct about the cause of the values.