在c中执行以下程序时出错

时间:2016-09-23 04:23:25

标签: 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次。

1 个答案:

答案 0 :(得分:1)

您正在写父母和子女的错误文件描述符。

以下一行:

elems

应该是:

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

事实上,你之前已经关闭了fp。