开发者

how can a function return two values

We know that 开发者_StackOverflow社区a c function never returns more than one value.Then how come the fork() function returns two values? How it is implemented?


fork() as a function only returns one value at a time - however, it creates a copy of your running executable, and returns a different value in each copy.


The fork() function starts a new process by duplicating the current one. If it works, fork() returns one thing from the parent process and another thing from the child process so that the remaining code knows which process is "this" process.

fork(), in a sense, does return two values, but not in the same sense as you might be thinking. Another function that does this type of thing is setjmp() (which returns 0 if returning directly and non-zero if we got here via longjmp()).

For a C function to return two values in the sense you're talking about, it is often done like this:

int return_2_values(int *other)
{
    *other = 2;
    return 1;
}

and invoked like this:

int b;
int a = return_2_values(&b);

/* a is now 1, and b is now 2 */

Here, return_2_values() is passing both return values to the same continuation, whereas fork() and setjmp() return one value each to two different continuations.


fork() only returns one value. It just returns different values different processes.

The implementation of this behavior is managed by the OS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜