Create a process and tell him to sleep?
What's the correct way to tell a specific sleep process? I am not quite clear on how to manage the various processes I create.
I am trying to make two processes sleep for 2 and 3 seconds. When process 1 has slept for 2 seconds and process 2 is still sleeping, I want process 3 to start sleeping. But how can I describe the sleep process? Or not me?
int main(void)
{
pid_t p1 = fork();
pid_t p2 = fork();
pid_t p3 = fork();
//make p1 sleep(2) and p2 sleep(3)
waitpid(p1, NULL, 0); //waiting for p1 to terminate
//make p3 sleep(2);
}
As you can see, I don't understand how to handle processes or what they really are. I kind of treat them as objects, but I'm guessing this is wrong. I tried reading a thing or two about this, but they contain over 9000 PDF pages. A simple explanation that I should see them would be appreciated, And yes, this is school material, but no, this is not an assignment.
source to share
Start with man fork
, which is slightly shorter than 9000 pages. The main thing is that successful fork
returns two times: it returns 0 to the child process and the child PID to the parent process. It is commonly used as follows:
pid_t pid = fork();
if (pid<0) { /* error while forking */
};
if (!pid) { /* code for child */
play();
whine();
sleep();
exit(0);
} else { /* code for parent */
grunt();
waitpid(...);
}
Usually you don't tell the child process about this, and you just add the code to the appropriate branch if
.
In your example, if all forks are successful, you get 8 processes:
- The first fork creates a new process,
p1
gets 0 in the new process and some pid in the parent. - The second fork is called in both the original parent and child, adding 2 images to the image.
p2
gets 0 in all "grandchildren" and two different pids in 2 processes that existed before step 2. - The third fork is called in four different processes, adding four more processes to the image.
source to share
You can post it first SIGSTOP
, then SIGCONT
I guess.
kill(p1, SIGSTOP);
Alternatively and more securely, since you only unlock and thus have full control over the code, you can handle paths:
if (in_child_1)
sleep(..);
As an additional note, there are more processes created in your code than you expect. The fact is that after creation p1
it launches from this point in parallel with the parent . Etc.
source to share