2010-12-06 78 views
0

我必須製作程序,這將使兩個子進程。這些進程將在文件中寫入一些東西(字符串...)。父進程應該決定其過程是要寫入文件 我已創建子進程,但我停留在這些信號和我沒有線索如何做到這一點子進程寫入文件

#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

如果這是功課,請標記爲這樣。你的問題到底是什麼?你是什​​麼意思,「卡住這些信號」?你在嘗試什麼,你卡在哪裏? – 2010-12-06 13:48:17

回答

1

首先你的子進程一旦創建就會退出。如果他們不這樣做,那麼第一個孩子會創建一個自己的孩子。你可能想在一個創建兒童for循環和做類似:

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

這是一個壞主意,你之前打開的文件叉()。您最終將擁有三個進程,這三個進程都擁有相同權限的相同文件的文件句柄。如果你這樣做,生活開始變得複雜!一般情況下,只有在真正需要時纔打開文件,並在完成使用後儘快關閉它們。


我覺得你的問題的意思是,你想要的父進程告訴孩子由家長髮送信號給孩子寫的。這樣做有更簡單的方法,但我想你的老師希望你演示如何用信號做到這一點。

首先,您需要編寫一個信號處理程序。有關如何執行此操作的更多信息,請參閱http://linux.die.net/man/2/signal

其次你需要真正發送信號。有關更多信息,請參閱http://linux.die.net/man/2/kill。請注意,名稱「kill」有點用詞不當。