避免ansi C中的SD卡损坏

use*_*852 5 c file-io can-bus sd-card embedded-linux

我目前正在开发用于数据记录的嵌入式Linux设备.Linux设备插入CANbus并将流量写入SD卡.

SD卡有时会损坏并以只读方式安装.需要避免这种行为.

文件系统是FAT(SD卡应该可以被Windows系统读取).

嵌入式设备可以随时断电,因此我需要一种安全的方法从我的C程序写入SD卡.

由于我不是真的进入C,我依赖一个名为"candump"的程序,它基本上以这种格式将canmessages打印到stdout:

<0x006> [8] 77 00 00 00 00 00 00 00
Run Code Online (Sandbox Code Playgroud)

我的C程序基本上打开了candump程序,从stdout读取,添加时间戳并删除不必要的字符:

1345836055.520 6 7700000000000000


while(running)
{
    if (filename != NULL)
    {
        fp_log = fopen(filename, "a");
        if (!fp_log) 
        {
            perror("fopen");
            exit (EXIT_FAILURE);
        }  
    }  

    fgets(line, sizeof(line)-1, fp);

    /* reset the row_values so they are always correctly initialized */
    row_identifier = 0;

    if (strchr(line,'<') != NULL)
    {
        /* creating a buffer char to store values for casting char to int*/
        buffer_ident[0] = line[4];
        buffer_ident[1] = line[5];

        /* cast buffer e.g. {'1','0','\0'} to int: 10 */
        row_identifier = strtol(buffer_ident,NULL,10);

        /* heartbeat of the CANBUS PLC */
        if(row_identifier == 80)
        {
            /* return pong on identifier 81 to the PLC */
            //system("cansend can0 -i 81 1 > /dev/null");
        }
        else
        {
            gettimeofday(&tv,NULL);
            fprintf(fp_log,"%d.%03d ", tv.tv_sec, tv.tv_usec/1000);
            fprintf(fp_log,"%d ",row_identifier);

            /* rowlenght > 11 = data part is not empty */
            row_lenght = strlen(line);
            if (row_lenght>11)
            {
                int i=0;
                for (i=11;i<row_lenght;i++)
                    /* remove spaces between the data to save space and copy data into new array */
                    if (isspace(line[i]) == 0)
                        fprintf(fp_log,"%c",line[i]);
            fprintf(fp_log,"\n");   
            }
        }
    }
    fclose(fp_log);

}
Run Code Online (Sandbox Code Playgroud)

上面的代码片段工作正常,只是我得到了SD卡损坏.

我最终使用ext3作为具有标准安装选项的文件系统.没有问题了

Avi*_*vio 1

发生损坏的原因可能是操作系统未完成其在 FAT 文件系统上的写入操作。正如J-16 SDiZ正确指出的那样,您可以尝试sync通过不时强制操作系统在文件系统上写入更改来缓解问题。

但是,您遇到此类问题是因为您没有使用日志文件系统(例如 Ext3 或 NTFS)。要做的另一件事是每次fsck启动时都对文件系统进行操作,然后显式rw强制重新挂载以保持挂载点干净且可写。