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.
}
You can use clone() (which is actually used by fork() itself). It lets you pass an arg to your entry function.
http://linux.die.net/man/2/clone
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 intmyvar
to each of two child processes but I want each to have a different value from the parent process:So doing this allows each process to have a "copy" of
myvar
with it's own value.If you didn't change the value, then each fork'd process would have the same value.
See the
exec()
family of functions.EDIT: If you're trying to initialize copies of the same program as the base process, just continue using variables as suggested by duskwuff.
Local and global variables are inherently preserved across a
fork()
, so there's no need to "pass arguments". If you're calling a function in the forked process, you can do something like:I'm late to respond, but here is how I do it:
First, you fork() the process to create a new process. It still has the same memory space as the old one. fork() returns for both parent and child processes. If fork() returns zero, you are the child process. The child process then uses execl() to replace the process memory with one from a new file.
Notice that progname is given twice to execl(). The first is what execl() will actually try to run, the second is argv[0]. You must provide both or the argument count will be off by one. Progname must contain all the required path information to find the desired executable image.
I give two arguments in this example, but you can pass as many as you want. it must be terminated with NULL, and I think you have to cast it as (char *) like I show.
This approach gives you a fully independent process with arguments and a unique pid. It can continue running long after the parent process terminates, or it may terminate before the parent.