学习在C ++中fork()空闲进程

时间:2014-03-28 08:49:47

标签: c++ linux fork sigchld

这是我编程问题的修订版:

  1. 分解两个随机时间运行的空闲进程,每个进程一次 在0 - 20秒之间运行。
  2. 进程应使用信号SIGSTOP和SIGCONT来安排 循环队列中的进程。
  3. 当子进程BOTH终止每个空闲进程时, 父母也应该终止。
  4. 如果其中一个子进程终止,它应该继续运行,直到 它们都使用SIGCHLD终止。
  5. 这是关于我到底有多远。

    #include <iostream>
    #include <unistd.h>
    #include <sys/wait.h>
    
    using namespace std;
    using std::cout;
    
    volatile sig_atomic_t keep_going = 1;
    
    void catch_child (int sig)
    { int status, p;
      p = waitpid(-1,&status,WNOHANG);
      if (p==0) return;
      keep_going=0;
      cout<<"Child process caught: "<< p <<endl;
      return;
    }
    
    
    int  main()
    {
      pid_t pid;
      pid_t mypid;
      int rand1;
    
      rand1 = rand()%20;    
    
      signal (SIGCHLD, catch_child);
    
      pid = fork();
      if (pid<0) {
        cout<<"Error\n";
        return 0;
      }
      else if (pid==0) {
    
    
        mypid = getpid();
        cout << "Child pid is " << mypid << "\n";
        execlp("./idle","./idle","1",rand1,0);
      } else {
        mypid=getpid();
    
        cout<<"parent procss is "<<mypid<<" and child is "<<pid<<"\n";
        sleep(5);
    
        cout<<"pausing child "<<pid<<" for 5 seconds\n";
        kill(pid,SIGSTOP);
    
        for (int i=0; i<5; i++) sleep(1);
    
        cout<<"Resuming child "<<pid<<"\n";
        kill(pid,SIGCONT);
    
        cout<<"Parent process pid is "<<mypid<<" waiting for child to stop\n";
        while (keep_going==1) sleep(1);
        // wait(NULL);
    
    
        cout <<"Parent knows that Child now done\n";
      }
      return 0;
    }
    

0 个答案:

没有答案