了解文件截断

引自Advanced Programming in the UNIX Environnement(第505页),第13.6节:

We need to truncate the file, because the previous instance of the
daemon might have had a process ID larger than ours, with a larger
string length. For examples , if the previous instance of the daemon
was process ID 12345, and the new instance is process ID 9999, when we
write the process ID to the file, we will be left with 99995 in the
file. Truncating the file prevents data from the previous daemon
appearing as if it applies to the current daemon.

这个评论是在这个功能上做出的:

already_running(void)
{
    int fd;
    char buf[16];
    fd = open(LOCKFILE, O_RDWR|O_CREAT, LOCKMODE);
    if (fd < 0) {
        syslog(LOG_ERR, "can't open %s: %s", LOCKFILE, strerror(errno));
        exit(1);
    }
    if (lockfile(fd) < 0) {
        if (errno == EACCES || errno == EAGAIN) {
            close(fd);
            return(1);
        }
        syslog(LOG_ERR, "can't lock %s: %s", LOCKFILE, strerror(errno));
        exit(1);
    }
    ftruncate(fd, 0);
    sprintf(buf, "%ld", (long)getpid()); 
    write(fd, buf, strlen(buf)+1);
    return 0;
}

我不明白这种行为是如何可能的,以及文件截断如何防止这种行为发生.有人可以解释一下吗?

谢谢回答!

解决方法:

在上面的示例中,文件最初为5个字节.当你打开它进行写入,并在不截断的情况下将字符串“9999”写入其中时,它将覆盖前4个字节,并保留第5个字节.因此该文件将显示为“99995”.截断将文件长度设置为0,从而有效地删除先前的内容.

上一篇:drop、truncate和delete的区别


下一篇:SQL中Truncate语法