本文介绍了如何将参数传递给fork()创建的进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C中的 fork()创建流程的副本.我不知道如何将参数传递给我的过程的副本.例如,我想将整数传递给流程副本.

I want to create copies of a process using fork() in C.I cant figure out how to pass arguments to the copies of my process.For example,I want to pass an integer to the process copies.

或者如果我有一个循环,我在其中调用fork()并想将唯一的值传递给进程(例如0 ... N),我该怎么办

Or I what to do, if I have a loop in which I call fork() and want to pass a unique value to processes (e.g. 0...N)

for (int i = 0; i < 4; ++i) {
    fork();
    // pass a unique value to new processes.
}

推荐答案

关于fork()的一个妙处是,您生成的每个进程都会自动获取父级拥有的所有内容的副本,因此,例如,我们要传递两个子进程中的每一个的int myvar,但我希望每个子进程都具有与父进程不同的值:

The nice part about fork() is that each process you spawn automatically gets a copy of everything the parent has, so for example, let's say we want to pass an int myvar to each of two child processes but I want each to have a different value from the parent process:

int main()
{
    int myvar = 0;
    if(fork())
        myvar = 1;
    else if(fork())
        myvar = 2;
    else
        myvar = 3;

    printf("I'm %d: myvar is %d\n", getpid(), myvar);
    return 0;
}

因此,这样做使每个进程都有一个myvar的副本"及其自己的值.

So doing this allows each process to have a "copy" of myvar with it's own value.

I'm 8517: myvar is 1
I'm 8518: myvar is 2
I'm 8521: myvar is 3

如果您不更改该值,则每个派生进程将具有相同的值.

If you didn't change the value, then each fork'd process would have the same value.

这篇关于如何将参数传递给fork()创建的进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:44