繁体   English   中英

仅当文件不存在时如何创建文件?

[英]How to create a file only if it doesn't exist?

我写了一个 UNIX 守护进程(针对 Debian,但它应该无关紧要),我想提供一些创建“.pid”文件(包含守护进程的进程标识符的文件)的方法。

我搜索了一种在文件存在时打开文件的方法,但找不到。

基本上,我可以这样做:

if (fileexists())
{
  //fail...
}
else
{
  //create it with fopen() or similar
}

但就目前而言,这段代码并没有以原子方式执行任务,这样做会很危险,因为另一个进程可能会在我的测试和文件创建过程中创建文件。

你们对如何做到这一点有任何想法吗?

谢谢你。

PS:仅涉及std::streams的解决方案的加分点。

人2打开:

O_EXCL 确保此调用创建文件:如果此标志与 O_CREAT 一起指定,并且路径名已存在,则 open() 将失败。 如果未指定 O_CREAT,则 O_EXCL 的行为未定义。

所以,你可以调用fd = open(name, O_CREAT | O_EXCL, 0644); /* Open() 是原子的。 (因为某种原因) */

更新:当然,您应该将 O_RDONLY、O_WRONLY 或 O_RDWR 标志之一 OR 到 flags 参数中。

我在这里学到了正确的守护进程(回到过去):

这是一个很好的阅读。 从那以后,我改进了锁定代码,以消除平台上允许使用指定特定区域进行咨询文件锁定的竞争条件。

这是我参与的一个项目的相关片段:

static int zfsfuse_do_locking(int in_child)
{
    /* Ignores errors since the directory might already exist */
    mkdir(LOCKDIR, 0700);

    if (!in_child)
    {
        ASSERT(lock_fd == -1);
        /*
         * before the fork, we create the file, truncating it, and locking the
         * first byte
         */
        lock_fd = creat(LOCKFILE, S_IRUSR | S_IWUSR);
        if(lock_fd == -1)
            return -1;

        /*
         * only if we /could/ lock all of the file,
         * we shall lock just the first byte; this way
         * we can let the daemon child process lock the
         * remainder of the file after forking
         */
        if (0==lockf(lock_fd, F_TEST, 0))
            return lockf(lock_fd, F_TLOCK, 1);
        else
            return -1;
    } else
    {
        ASSERT(lock_fd != -1);
        /*
         * after the fork, we instead try to lock only the region /after/ the
         * first byte; the file /must/ already exist. Only in this way can we
         * prevent races with locking before or after the daemonization
         */
        lock_fd = open(LOCKFILE, O_WRONLY);
        if(lock_fd == -1)
            return -1;

        ASSERT(-1 == lockf(lock_fd, F_TEST, 0)); /* assert that parent still has the lock on the first byte */
        if (-1 == lseek(lock_fd, 1, SEEK_SET))
        {
            perror("lseek");
            return -1;
        }

        return lockf(lock_fd, F_TLOCK, 0);
    }
}

void do_daemon(const char *pidfile)
{
    chdir("/");
    if (pidfile) {
        struct stat dummy;
        if (0 == stat(pidfile, &dummy)) {
            cmn_err(CE_WARN, "%s already exists; aborting.", pidfile);
            exit(1);
        }
    }

    /*
     * info gleaned from the web, notably
     * http://www.enderunix.org/docs/eng/daemon.php
     *
     * and
     *
     * http://sourceware.org/git/?p=glibc.git;a=blob;f=misc/daemon.c;h=7597ce9996d5fde1c4ba622e7881cf6e821a12b4;hb=HEAD
     */
    {
        int forkres, devnull;

        if(getppid()==1)
            return; /* already a daemon */

        forkres=fork();
        if (forkres<0)
        { /* fork error */
            cmn_err(CE_WARN, "Cannot fork (%s)", strerror(errno));
            exit(1);
        }
        if (forkres>0)
        {
            int i;
            /* parent */
            for (i=getdtablesize();i>=0;--i)
                if ((lock_fd!=i) && (ioctl_fd!=i))       /* except for the lockfile and the comm socket */
                    close(i);                            /* close all descriptors */

            /* allow for airtight lockfile semantics... */
            struct timeval tv;
            tv.tv_sec = 0;
            tv.tv_usec = 200000;  /* 0.2 seconds */
            select(0, NULL, NULL, NULL, &tv);

            VERIFY(0 == close(lock_fd));
            lock_fd == -1;
            exit(0);
        }

        /* child (daemon) continues */
        setsid();                         /* obtain a new process group */
        VERIFY(0 == chdir("/"));          /* change working directory */
        umask(027);                       /* set newly created file permissions */
        devnull=open("/dev/null",O_RDWR); /* handle standard I/O */
        ASSERT(-1 != devnull);
        dup2(devnull, 0); /* stdin  */
        dup2(devnull, 1); /* stdout */
        dup2(devnull, 2); /* stderr */
        if (devnull>2)
            close(devnull);

        /*
         * contrary to recommendation, do _not_ ignore SIGCHLD:
         * it will break exec-ing subprocesses, e.g. for kstat mount and
         * (presumably) nfs sharing!
         *
         * this will lead to really bad performance too
         */
        signal(SIGTSTP,SIG_IGN);     /* ignore tty signals */
        signal(SIGTTOU,SIG_IGN);
        signal(SIGTTIN,SIG_IGN);
    }

    if (0 != zfsfuse_do_locking(1))
    {
        cmn_err(CE_WARN, "Unexpected locking conflict (%s: %s)", strerror(errno), LOCKFILE);
        exit(1);
    }

    if (pidfile) {
        FILE *f = fopen(pidfile, "w");
        if (!f) {
            cmn_err(CE_WARN, "Error opening %s.", pidfile);
            exit(1);
        }
        if (fprintf(f, "%d\n", getpid()) < 0) {
            unlink(pidfile);
            exit(1);
        }
        if (fclose(f) != 0) {
            unlink(pidfile);
            exit(1);
        }
    }
}

另见http://gitweb.zfs-fuse.net/?p=sehe;a=blob;f=src/zfs-fuse/util.c;h=7c9816cc895db4f65b94592eebf96d05cd2c369a;hb=refs/heads/maint

我能想到的唯一方法是使用系统级锁。 看这个: C++如何检查文件是否在使用中——多线程多进程系统

解决此问题的一种方法是打开文件进行追加。 如果函数成功并且位置为 0,那么您可以相当确定这是一个新文件。 可能仍然是一个空文件,但这种情况可能并不重要。

FILE* pFile = fopen(theFilePath, "a+");
if (pFile && gfetpos(pFile) == 0) { 
  // Either file didn't previously exist or it did and was empty

} else if (pFile) { 
  fclose(pFile);
}

似乎没有办法严格使用流来做到这一点。

相反,您可以使用 open (如wildplasser 上面提到的),如果成功,继续打开与流相同的文件。 当然,如果您写入文件的所有内容都是 PID,则不清楚为什么不使用 C 风格的 write() 来编写它。

O_EXCL 仅排除尝试使用 O_EXCL 打开同一文件的其他进程。 当然,这意味着您永远不会有完美的保证,但是如果文件名/位置在其他人不可能打开的地方(除了您认识的使用 O_EXCL 的人),您应该没问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM