Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments to processes created by 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.

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.
}
like image 281
Basti Avatar asked Nov 19 '12 20:11

Basti


1 Answers

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.

like image 162
Mike Avatar answered Sep 23 '22 09:09

Mike