[英]Getting an error while executing the below program in c
#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次。
您正在父級和子級中寫入錯誤的文件描述符。
下一行:
fprintf(fp, "%d", i++);
應該:
fprintf(fp1, "%d", i++);
確實,您之前已經關閉了fp。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.