2016-09-23 85 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之前关闭。

相关问题