I’m looking to run multiple concurrent processes in a C program. The programs will take arguments from the user and then execute each argument as a child process. I think that means that all I need to do is ensure that the fork() is performed by the original parent process each time, and then each of the resultant child processes will run at the same time, and not sequentially.
Am I correct in thinking this? And can anyone let me know how I might go about doing it?
Forgive me for diverting from the matter at hand in my previous answer (by suggesting the use of threads). Since I’m going in a completely new direction here, I feel compelled to add this as a separate answer.
Short version:
Please make the following changes in your program:
Long version:
(1) By the variable
length, I presume you want to get the total number of arguments.argvis apointer-to-char-pointer, and as such is simply a memory address. If you print out the length in your program, you will notice it is always 4 (or whatever is the size of a memory address in your system).So this:
Should really be this:
argcholds the total number of arguments passed when executing the process. For example,gives: argc = 3 (and not 2, a very common pitfall)
(2) Another issue with your program, is the
execvpcall.The prototpye for the execvp is as follows:
where, argv is the list of arguments passed to the new command, very similar to the argv in your own program.
What you use in your program is:
Suppose
i=1andargv[1] = "/bin/ls".What this command does is look for the
/bin/lsexecutable & pass a NULL pointer (0) to it. This may lead to the following runtime error:Referring to the exec man page,
Though it is not mandatory to pass the filename again, you certainly shouldn’t pass a NULL pointer. Since you don’t want to pass any arguments, I suggest you use the following
execlcall, instead:Remember that all such calls are finally converted to
execve()finally & then executed, making them equivalent eventually.I encourage you to read more about the exec family of functions using
man.