2017-10-29 10 views
-1
#include <sys/types.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <sys/resource.h> 
#include <errno.h> 
int main() 
{ 
    int pid; 
    int temp = 0; 
    while(1){ 
    pid = fork(); 
    if(pid == 0) 
    return 0; 
    if(pid == -1){ 
     if (errno == EAGAIN) 
     printf("%d \n limit process", (int)temp); 
    exit(-1);} 
    temp++; 
    } 
     return 0; 
} 

ここは私のコードです。しかし教師はそれが間違っていて、if(pid == 0)の条件体で何かが間違っていると言った。私を助けてください。ありがとうございました!Linuxでの親プロセスの最大数のカウント

+1

おそらく欠けています'{}'を使って適切なブロックをマークします。 – Ron

答えて

0

fork()は、子プロセスの場合は0、親プロセスの場合は>0、エラーの場合は負の値を返します。

子プロセスはすぐに終了します。実際には、複数のプロセスが同時にフォークされて終了するため、同時にプロセスを生成することはありません。

あなたがしたいことは、親がシャットダウンするように指示するまで(例えばシグナル経由で)子プロセスを実行し続けることです。

if (0 == pid) { 
    // I am child process -> wait until signal 
    // for example: sleep(MAX_INT); 
} 

親プロセスでは、テストが終了したらすべての子プロセスをシャットダウンする必要があります。たとえば、あなたは一つのプロセスグループに子プロセスのすべてを置くことができ、それに信号を送る:

if (pid == -1) { 
    if (errno == EAGAIN) { 
     // print output 
     printf("%d \n limit process", temp); 
     // kill all child processes (you 
     kill(0, SIG_TERM); // you might need to set up signal handler in parent process too - see 'signal') 
     // wait for child processes to finish and cleanup (we know there is 'temp' count of them); 
     for (int = 0; i < temp; ++i) { 
     wait(NULL); 
     } 
    } 
    } 

参考文献:

http://man7.org/linux/man-pages/man2/kill.2.html

http://man7.org/linux/man-pages/man2/waitpid.2.html

http://man7.org/linux/man-pages/man2/signal.2.html

+0

私はそれをどのように実装すべきですか?私はどんなコマンドを使うべきですか?申し訳ありませんが、私はそれらのシグナルとプロセスにはnoobieです:( –

関連する問題