2013-03-23 55 views
2

如果我運行這個程序,我會有死去的進程嗎?我正在嘗試創建一個運行5進程並行的主程序,然後不會得到不可用的進程。麻煩主要是要確定這沒有發生。我不太確定我是否正確地做到這一點。我聽說最好的做法是通過讓你的進程「等待()」來處理已經「fork()」的許多子進程,以確保你沒有停止進程。不存在的進程,fork()

#include <time.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <stdlib.h> 

void forkChildren(int nrofChildren, int *nr_of_children) { 
    pid_t pid; 
    int i; 
    for(i=0; i<5; i++) { 
     /* fork a child process */ 
     pid = fork(); 
     (*nr_of_children)++; 
     /* error occurred */ 
     if (pid < 0) { 
      fprintf(stderr, "Fork failed\n"); 
      exit(-1); 
     } 
     /* successful child */ 
     else if (pid == 0) { 
      int sleeptime=1; //rand()%10; 
      printf("I am child: %d \nwith parent: %d \nin loop: %d \nand will sleep for: %d sec\n\n", getpid(), getppid(), i, sleeptime); 
      sleep(sleeptime); 
      printf("Ending of child: %d \nwith parent :%d in loop: %d\n\n", getpid(), getppid(), i); 
     } 
     /* parent process 
     else { 
      wait(NULL); Do I need this to make sure I dont get defunct processes??? 
     } */ 
    } 
} 


int main(int argc, char *argv[]) { 
    srand((unsigned int)time(NULL)); 
    int nr_of_children=0; 
    if (argc < 2) { 
     /* if no argument run 5 childprocesses */ 
     forkChildren(5, &nr_of_children); 
    } else { 
     forkChildren(atoi (argv[1]), &nr_of_children); 
    } 
    wait(NULL); 
    printf("End of %d, with %d nr of child-processes\n\n", getpid(), nr_of_children); 
    return 0; 
} 
+0

*全部*過程在終止後變爲無效。如果你「等待」他們,他們會在很短的時間內成爲殭屍。如果你離開或從主隊返回,他們將在很短的時間內成爲殭屍,因爲他們將被等待他們的初始化人接受。 – 2013-03-23 13:51:15

+0

爲什麼不使用返回值來將生成的孩子的數量傳遞給調用者,而不是使用具有指向結果的愚蠢的'* nr_of_children'指針的void()函數? – wildplasser 2013-03-23 13:54:16

+0

@wildplasser啊哈,這是一個想法,我沒有想過,謝謝:-) – patriques 2013-03-23 13:56:38

回答

3

是的,您需要wait上的子進程。原因是,否則仍會有與現在殭屍進程相關的數據,例如進程返回值的空間。

+1

那麼你的意思是我必須在else語句中等待(NULL)以確保它? – patriques 2013-03-23 13:54:31

+1

@patriques是的,否則你會在系統中徘徊「殭屍」進程。 – 2013-03-23 13:55:26

+0

謝謝,這是我想知道的.. – patriques 2013-03-23 14:02:38

0

看看使用daemon()命令將您的應用放在後臺,然後使用pthreads來管理並行性。

NAME 守護 - 在後臺運行

概要 的#include

int daemon(int nochdir, int noclose); 

功能測試宏要求的glibc(見 feature_test_macros(7)):

daemon(): _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500) 

描述 daemon()函數用於程序希望從控制終端分離自己並在後臺運行的系統守護進程 。

If nochdir is zero, daemon() changes the process’s current working directory to the root directory ("/"); otherwise, 

    If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made 

這些文件描述符。