2010-12-06 12 views
0

私は2つの子プロセスを作るプログラムを作る必要があります。これらのプロセスは何か(文字列...)をファイルに書き出します。親プロセスは、私が子供のプロセスを作成した をファイルに書き込むしようとしているプロセスを決める必要がありますが、私はこれらの信号で立ち往生していると私はどのようにこの子プロセスがファイルに書き込む

#include <stdio.h> 
#include <signal.h> 
#include <stdlib.h> 
#define READY_SIGNAL SIGUSR1 
#define max 1000 
int main(int argc, char *argv[]) { 
     FILE *file; 
     int o; 
     char *name; 
    opterr = 0; 
     while ((o = getopt(argc, argv, "hp:")) != -1) 
       switch (o) { 
         case 'h': 
         Help(); 
         exit(1); 

         default: 
       exit(1); 
     } 
    argc -= optind; 
    argv += optind; 
     if(argc==0){ 
     printf("file name\n"); 
     scanf("%s",&name); 
     file=fopen(name,"a+"); 
     if(file != NULL) 
     { 
       printf("file created\n"); 
       // fclose(file); 
     } 

     else printf("the file does not exist\n"); 

     } 
     else if(argc>1) { 
       return(1); 
     } 
     else 
       meno=argv[0]; 
     file=fopen(name,"a"); 
     if(file != NULL){ 
     printf("file created\n"); 
     } 
     else printf("the file does not exist\n"); 

pid_t child_pid, child_pid2; 

printf ("the main program process ID is %d\n", (int) getpid()); 

child_pid = fork() ; 
if (child_pid != 0) { 
    printf ("this is the parent process, with id %d\n", (int) getpid()); 
    printf ("the child's process ID is %d\n",(int) child_pid); 
} 
else { 
    printf ("this is the child process, with id %d\n", (int) getpid()); 
exit(0); 
} 

child_pid2 = fork() ; 
if (child_pid2 != 0) { 
    printf ("this is the parent process, with id %d\n", (int) getpid()); 
    printf ("the child's process ID is %d\n",(int) child_pid2); 
} 
else 
{ 
    printf ("this is the child process, with id %d\n", (int) getpid()); 
    exit(0); 
} 
return 0; 

} 

感謝を行うための手掛かりを持っていない

+0

宿題の場合は、そのまま宿題にしてください。あなたの質問は何ですか?あなたは「これらの信号に固執しています」という意味はどうですか?あなたは何をしようとしていますか? –

+0

信号でどこから始めるべきかわかりません... – johnySA

答えて

1

子プロセスは、作成されるとすぐに終了します。彼らがしなかった場合、最初の子供はそれ自身の子供を作成します。あなたが()をforkする前に、ファイルを開くには悪い考えである

if(child_pid[i] != 0) 
{ 
    /* This is the parent. */ 
} 
else 
{ 
    /* This is the child. */ 
    do_child_stuff(); 
    exit(0); 
} 

:あなたは、おそらくループのために子を作成し、同じような何かをしたいです。同じアクセス権を持つ同じファイルに対するファイルハンドルをすべて保持する3つのプロセスが終了します。あなたがそれをするなら、人生は複雑になり始めます!一般的には、本当に必要なときだけファイルを開き、ファイルの使用を終了するとすぐにファイルを閉じます。


あなたの質問が意味することは、親プロセスが、親から子への信号を送信することによって、子プロセスに書き込むように伝えたいということです。これを行う簡単な方法がありますが、あなたの先生は信号でそれを行う方法を実演することを望んでいると思います。

まず、シグナルハンドラを作成する必要があります。これを行う方法の詳細については、http://linux.die.net/man/2/signalを参照してください。

第2に、実際に信号を送信する必要があります。詳細については、http://linux.die.net/man/2/killを参照してください。 「kill」という名前はちょっとした誤解であることに注意してください。

関連する問題