为什么输出打印两次? [英] Why the output is printing twice?

查看:317
本文介绍了为什么输出打印两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能看起来幼稚的大部分你,但我无法理解这一小块code的。

May be it look childish for most of you but I am unable to understand this small piece of code.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char** argv) {
    int i, pid;
    pid = fork();
    printf("Forking the pid: %d\n",pid);
    for(i =0; i<5; i++)
        printf("%d  %d\n", i,getpid());
    if(pid)
        wait(NULL);
    return (0);
}

这一计划的投放是

Out put of this program is

Forking the pid: 2223
0  2221
1  2221
2  2221
3  2221
4  2221
Forking the pid: 0
0  2223
1  2223
2  2223
3  2223
4  2223
Press [Enter] to close the terminal ...

在for循环printf命令使用一次。为什么分叉的PID,并认为PID的印后两次。这是如何工作的?任何人都可以解释我这个?提前致谢。
任何人都可以解释我为什么我们要使用在这里等?我从该名男子的网页了解的就是等待retuns控制到父进程?是我的理解是正确的?是否有必要使用一个分叉过程之后等待?
操作系统:Ubuntu中,编译器:GCC,IDE:NetBeans的

In the for loop the printf command is used once. Why "Forking the pid" and after that the pid's are printed twice. How this is working? Can anybody explain me this? Thanks in advance. Can anybody explain me why we have to use wait here? What I understood from the man pages is wait retuns the control to parent process? Is what I understood is correct?Is it necessary to use wait after forking a process? Operating system : ubuntu, compiler : gcc, IDE : netbeans

推荐答案

但是,这到底是什么一样。您分支的过程,一切后叉,是因为现在你必须执行相同的印刷code两个过程做两次。你基本上是问为什么叉。 叉因为应该叉。这就是它是。

But that' exactly what fork does. You forked the process and everything after the fork is done twice because now you have two processes executing the same printing code. You are basically asking why fork forks. fork forks because is is supposed to fork. That's what it's for.

父和子进程一般执行的并行的,也就是说,你在你的例子中看到漂亮的连续输出不保证。你可能很容易从两个进程结束了与线交错式输出。

After fork the parent and the child processes are generally executed in parallel, meaning that the nice sequential output you see in your example is not guaranteed. You might have easily ended up with line-interleaved output from two processes.

在您的情况等待函数只从父进程执行。这使得它等到子进程结束,只有父进程进行终止,以及之后。在这个特殊的例子调用是不是真的重要,因为在此之后,程序什么也不做,只是终止。但是,例如,如果你想收到孩子过程中的一些反馈给父进程,并做了父进程的反馈一些额外的工作,你必须使用来等待子进程完成执行。

wait function in your case is executed from the parent process only. It makes it wait until the child process terminates, and only after that the parent process proceeds to terminate as well. Calling wait in this particular example is not really critical, since the program does nothing after that, it just terminates. But, for example, if you wanted to receive some feedback from the child process into the parent process and do some additional work on that feedback in the parent process, you'd have to use wait to wait for the child process to complete its execution.

这篇关于为什么输出打印两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆