'Fork n process and reorder execution of "ls" command by each child process
I have an int array that first element of that array is defining number of process that I want to fork. Other next elements representing the priority of executing a command by each process. e.g. if second element of that array is 1, it means that the first fork process should first run the command and after finishing the work next process which has "2" priority should run the command.
for(int i=0;i<pr_array[0];i++)
{
if(fork() == 0)
{
pr_pid_array[i]=getpid();
execlp("/bin/ls","ls",NULL);
exit(0);
}
}
I don't know how to keep this synchronization. I don't want to use semaphore.
Solution 1:[1]
Semaphores seems to be the best solution in my opinion, anyway you can also use other synchronization methods.
You could use a shared memory that holds your array, when i-th work is completed you will replace sharedArray[i] with a defunct value that means the work has finished.
In this way each process knows that i-th work is finished and i+1 can start. If you are in a Unix system you can use shm documentation
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniele Affinita |
