Create a process and tell it to sleep? Create a process and tell it to sleep? unix unix

Create a process and tell it to sleep?


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's PID to the parent process. It's typically used like this:

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(...);}

You don't normally tell the child process to do this and that, you just add code doing it to the appropriate if branch.

In your example, if all forks are successful, you end up with 8 processes:

  1. First fork creates a new process, p1 gets 0 in the new process and some pid in the parent.
  2. Second fork is called both in the original parent and in the child, adding 2 processes to the picture.p2 gets 0 in all "grandchildren" and two different pids in 2 processes existing before step 2.
  3. Third fork is called in four different processes, adding four other processes to the picture.


You could send it a SIGSTOP and then a SIGCONT I think.

kill(p1, SIGSTOP);

Alternatively and more sanely, since you're only forking and thus have complete controll over the code, you could handle the paths:

if (in_child_1)    sleep(..);

As a side note, in your code more processes are created than you expect. The thing is once p1 is created it starts executing from that point, in parallel with its parent. And so on.