它是如何可能的fork()的返回两个值? [英] How is it possible for fork() to return two values?

查看:180
本文介绍了它是如何可能的fork()的返回两个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于在C函数只返回一个值,所有的时间,怎么能叉(),这也是一个函数,返回两个值?

Since a function in C returns only one value, all the time, how can fork(), which is also a function, return two values?

推荐答案

如果你读,构建和运行下面的程序,你应该得到是怎么回事的一个更好的主意。

If you read, build, and run the following program you should get a better idea of what is going on.

#include <stdio.h>
#include <unistd.h>

int main(void) {
    pid_t fk;

    printf("\tbefore fork my pid = %lu\n", (unsigned long)getpid() );

    fflush(stdout); /* This may keep the above print
                       statement from outputing twice. */

    fk = fork(); /* The OS kernel makes a copy of the current process here */

    printf("fork returned %lu and now my pid = %lu\n",
                         (unsigned long)fk, (unsigned long)getpid() );

    return 0;
}

之所以说 fflush(标准输出)需要的是,由于过程是通过fork这意味着,通过标准输入输出标准输出做缓冲被复制为好。在\\ N在第一次print语句的结束可能使其继续前进,刷新标准输出,但这不能保证。

The reason that the fflush(stdout) is needed is that since the process is duplicated by fork that means that the buffering done for stdout by stdio is duplicated as well. The "\n" at the end of that first print statement may make it go ahead and flush stdout, but this isn't guaranteed.

这篇关于它是如何可能的fork()的返回两个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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