【问题标题】:Getting an error while executing the below program in c在c中执行以下程序时出错
【发布时间】:2016-09-23 04:23:25
【问题描述】:
#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 次。

【问题讨论】:

  • 您介意格式化您的代码以使其可读吗?缩进,for(x;y;z) 很糟糕,而for (x; y; z;) 更易读。此外,如果文件不存在,fopen() 将返回 NULL。您必须在fopen() 之后检查。
  • 有一点,声明fprintf(fp, "%d", i++);应该改成fprintf(fp1, "%d", i++);?使用调试器诊断代码中的问题。
  • 除了第一个 printf 之外,父子代码似乎相同。所以只有第一个 printf 需要在 if / else 块中。
  • 您已经设置了一个竞争条件,其中包括:父母和孩子都可以随意读写文件,可能同时进行。这可能最终会将 + 60 打印为i,如果不是这样的话:fprintf(fp, "%d", i++);,实际上永远不会增加i在文件中,因为您使用后缀增量。它读取 i 的前一个值,将其用作写入的值,然后递增。
  • 使用选项 -g 编译,然后使用 GBD (gdb) 运行程序。在它崩溃后执行bt &lt;enter&gt; 并找到导致程序崩溃的代码行及其调用堆栈。

标签: c


【解决方案1】:

您在父级和子级中都写入了错误的文件描述符。

下面一行:

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

应该是:

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

确实你之前已经关闭了fp。

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 2016-01-06
    • 2013-12-09
    相关资源
    最近更新 更多