2017-02-01 2 views
1
#include<stdio.h> 
#include<unistd.h> 
#include<stdlib.h> 

int main(int argc, char ** argv) 
{ 

    int pid; 
    int status; 
    pid = fork(); 

    if (pid < 0) 
    { 
     printf("Cannot create a child process"); 
     exit(1); 
    } 
    else if (pid == 0) 
    { 

     printf("I am the child process. %d \n", getpid()); 
     printf("The child process is done. \n"); 
     fflush(stdout); // it does not write immediately to a disk. 
     exit(0); 
    } 
    else 
    { 

     printf("I am the parent process.%d \n", getpid()); 
     sleep(5); // sleep does not works 
     pid = wait(&status); // want to wait until the child is complited 
     printf("The parent process is done. \n"); 
     fflush(stdout); // it does not write immediately to a disk. 
     exit(1); 
    } 
} 

こんにちは、私は現在、子プロセスを作成しようとしています。しかし、これまでのところ、私が今試みていることは、まず子供を実行してプリントアウトし、常に「親プロセスが完了しました」というメッセージをプリントアウトすることです。現在 Cで親の前に子を実行

I am the parent process.28847 
I am the child process. 28848 
The child process is done. 
The parent process is done. 

はこれを印刷している:それは私の最初の時間
I am the parent process.28847 
The parent process is done. 
I am the child process. 28848 
The child process is done. 

ある

使用に私は睡眠を試してみました(&状態を)待ってました、私がやっているものに本当に自信を持っていないですので、フォーク子プロセスが終了するまで待ってから親プロセスを実行しますが、何かが機能していません。

P.S.スタックレイアウトを使用して申し訳ありません。

+4

あなたはおそらく使用する必要があります[ '待機()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html)または ['waitpid()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/waitpid.html)。 –

+3

あなたのコードでは、「親プロセスが完了しました」が(wait()を使用しているため)最後に印刷されます。 – usr

+0

ありがとう、私はそれを修正するために管理しています。私はミューテックスとセマフォをチェックするつもりですが、どのように改善することができますか? –

答えて

1

try waitpid(-1、NULL、0);または待ち(NULL)。これにより、すべての子プロセスが終了するまで親をブロックします。 これが機能する場合、スリープを使用する必要はありません。あなたのコードに

若干の変更:

else 
{ 
    int status =0; 
    printf("I am the parent process.%d \n", getpid()); 
    status= waitpid(-1, NULL, 0); // want to wait until the child is complete 
    //Also check if child process terminated properly 
    if(status==0) 
    { 
     printf("Child process terminated properly"); 
    } 
    else 
    { 
     printf("Child process terminated with error"); 
    } 

    printf("The parent process is done. \n"); 

    fflush(stdout); // it does not write immediately to a disk. 

    exit(1); 
} 
関連する問題