How to pass arguments to processes created by fork()

Basti picture Basti · Nov 19, 2012 · Viewed 23.4k times · Source

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.

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.
}

Answer

Mike picture Mike · Nov 19, 2012

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;
}

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.