在后台分叉无法正常工作 [英] fork in background don't work correct

查看:82
本文介绍了在后台分叉无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行此编.在前景和背景中:

I run this prog. in foreground and background:

int main()    
{
    int pid;
    printf("App Start pid=%d!\n",getpid());

    while(1) {
        pid=fork();
        if(pid==0) {
            printf("Child\n\n");
            exit(0);
        }
        else if(pid>0) {
            printf("Parent\n");
        }    
        sleep(1);
    }
}

在前台:

$ ./fork

结果是:

App Start pid=1360!    
Parent    
Child    
Parent    
Child    
...

在后台:

$./fork > out.txt &
$cat out.txt    
App Start pid=1368!    
Child    
App Start pid=1368!    
Parent    
Child    
App Start pid=1368!    
Parent    
Parent    
Child    
...

为什么应用程序在后台重启"? 我不明白发生了什么. 如何使fork在后台应用程序中正常工作? 谢谢

Why does the app 'restart' in background? I don't understand what happening. How can i make fork to work correctly in background app? Thanks

推荐答案

这与输出缓冲区有关:新创建的进程正在覆盖其父级print编写的内容.请注意,该消息不会更改,即:始终为App Start pid=1368!.

This has to do with the output buffers: newly created process are writing over and over what their parent already printed. Notice that the message does not change, i.e.: it is always App Start pid=1368!.

在第一次调用printf()之后放置fflush(stdout):

Place fflush(stdout) after the first call to printf():

printf("App Start pid=%d!\n",getpid());
fflush(stdout);

这样,在创建子进程之前,将清空 输出缓冲区.

This way the output buffer will be flushed before creating the children processes.

请注意,通过启动fork程序而不重定向stdout(即:$ ./fork),默认情况下stdout行缓冲的.因此,每次stdout收到换行符时,都已经执行了刷新stdout.

Note that by starting the fork program without redirecting stdout (i.e.: $ ./fork), stdout is line-buffered by default. For that reason, a flush of stdout is already performed every time it receives a new-line character.

这篇关于在后台分叉无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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