2016-09-23 50 views
0
#include <sys/types.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <sys/wait.h> 

int main() 
{ 
    /* Create the pipe */ 
    pid_t pid; 
    int k; 
    pid = fork(); 

    if (pid < 0) 
    { 
     printf ("Fork Failed\n"); 
     return -1; 
    } 

    for(k=0;k<60;k++) 
    { 
     if (pid == 0) 
     { 

      printf("I'm the child\n"); 
      printf("my pid is %d\n",getpid()); 
      FILE *fp,*fp1; 
      int i; 


      /* open the file */ 

      fp = fopen("File1.txt ", "r"); 

      fscanf(fp, "%d", &i) ; 
      printf("i: %d and pid: %d",i,pid); 
      fclose(fp); 
      fp1= fopen("File1.txt ", "w"); 

      fprintf(fp, "%d", i++); 

      fclose(fp1); 
      sleep(1); 
     } 
     else 
     { 
      printf("I'm the parent\n"); 
      printf("my pid is %d\n",getpid()); 
      FILE *fp,*fp1; 
      int i; 
      int y; 

      /* open the file */ 

      fp = fopen("File1.txt ", "r"); 

      fscanf(fp, "%d", &i) ; 
      printf("i: %d and pid: %d",i,pid); 
      fclose(fp); 
      fp1= fopen("File1.txt ", "w"); 

      fprintf(fp, "%d", i++); 

      fclose(fp1); 
      sleep(1); 
     } 


    } 
    return 0; 
} 

我得到一個錯誤,即執行此代碼後轉儲錯誤核心轉儲。我想知道我做錯了什麼。我的主要格言是:我想讀取包含數字1並打印該數字的文件。 我想編寫相同的文件並將該編號增加1.在此之後,孩子或父母進入睡眠模式,然後父母或孩子再次執行相同的過程。該過程持續高達60次。在c中執行下面的程序時出現錯誤

+2

你介意格式化你的代碼,使其可讀?縮進和'for(x; y; z)'是很可怕的,相反'for(x; y; z;)'更具可讀性。另外,如果文件不存在,'fopen()'返回NULL。你必須在'fopen()'之後檢查。 –

+3

一點,fprintf(fp,「%d」,i ++);'應該改爲'fprintf(fp1,「%d」,i ++);'?使用調試器來診斷代碼中的問題。 – putu

+0

除了第一個'printf',代碼似乎對於父母和孩子是相同的。所以只有第一個'printf'需要放在'if/else'塊中。 – user3386109

回答

1

您正在向父節點和子節點寫入錯誤的文件描述符。

以下行:

fprintf(fp, "%d", i++); 

應該是:

fprintf(fp1, "%d", i++); 

事實上你已經FP之前關閉。