2016-04-26 42 views
1

今天,我得到了一個項目,被告知做如下(我下面的代碼粘貼):Ç - 如何創建一個程序,它是很難「殺」

蟑螂是出了名的難殺。您的任務是創建一個非常難以殺死的蜂鳴器程序,其中有兩個進程。 基本上是:

  1. 的父進程派生了子和嗶聲的孩子隻手表父親每0.5秒(檢查usleep()
  2. 如果孩子死了父親叉另一個
  3. 如果父親去世了孩子叉一個新的子並假定父親
  4. 的角色都停止,如果任何兩個接收SIGTERM

顯示屏上ST的消息dout或stderr每次發生什麼事情, 將進程ID添加到每條消息,以便我們知道哪個進程 發出它。

我能解決前兩個問題,但我無法解決3和4.我對於4有點想法,但甚至不知道從哪裏開始3.任何建議?

#define SLEEP_TIME 500000 
static int keepGoing = 1; 
int main() { 
    //signal(SIGALRM,(void (*))kill_child); 
    //useconds_t nap = .5; 
    int nap = SLEEP_TIME; 
    int status; 
    pid_t child_pid = -1; 

    while(keepGoing == 1){ 
     //signal(SIGTERM, sig_handler); 
     //signal(SIGCHLD, sig_handler); 

     if(child_pid != 0){//&& getppid() != 1){ 
      printf("Beep\n"); 
      printf("Parent: %d\n", getpid()); 
      child_pid = fork(); 

      pid_t deleted = wait(&status); //Get the ID of anything that was killed 

      if(deleted != -1){ 
       printf("\nChild %d was killed\n", deleted); //Print it out 
      } 
     }else if(getppid() != 1){ 
      printf("Child: %d\n", getpid()); 
      //childHandler(child_pid); 
      usleep(nap); //Sleep every .5sec 
     }else{ //The parent was killed 
      printf("\nParent was deleted %d is the new parent\n", getpid()); 
      child_pid = fork(); 
      pid_t deleted = wait(&status); //Get the ID of anything that was killed 

      if(deleted != -1){ 
       printf("\nChild %d was killed\n", deleted); //Print it out 
      } 
      sleep(5); 
     } 

    } 
    return 0; 
} 
+0

嗯....一旦程序開始運行,您將被感染。 – randominstanceOfLivingThing

回答

0

我的有些想法爲4,但甚至不知道從哪裏開始就3.任何建議 ?

你的程序已經滿足了3

對於4:取消//signal(SIGTERM, sig_handler);main之前插入

#include <signal.h> 
void sig_handler(int signum) { kill(0, SIGKILL); } 

kill(0, SIGKILL)終止調用進程(父或子)的進程組中的每個進程。通過一個瞭解作業控制的shell,比如bash,只需要這麼做,因爲你的beeper進程組成了一個進程組。對於不知道作業控制的外殼,如灰燼,請在main()開始時加上setpgrp(); - 請參閱Process groups

相關問題