示例#1
0
//checks if file is locked by another process (if locked by the same process returns false)
bool LockFile::isLocked()
{
    fd = open(file_name.toUtf8(), O_RDONLY);
    if(fd < -1) {
        perror("open");
        return false;
    }
    return (lockf(fd, F_TEST, 0) != 0);
}
示例#2
0
void write_pid(const char *path, pid_t pid)
{
	int fd;
	int ret;

	fd = open(path, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);

	/* tant que le fichier est locké attendre */
	while((ret = lockf(fd, F_TEST, sizeof(pid_t))) && errno == EAGAIN)
		sleep(1);

	/* lock, write, unlock */
	lockf(fd, F_LOCK, sizeof(pid_t));
	write(fd, &pid, sizeof(pid));
	lseek(fd, 0, SEEK_SET);
	lockf(fd, F_ULOCK, sizeof(pid_t));
	close(fd);
}
示例#3
0
文件: porting.c 项目: dong1/testsize
/*
 * lock_region() - lock/unlock region of a file
 *   return: 0 if success, -1 otherwise
 *   fd(in): file descriptor
 *   cmd(in): locking command to perform
 *   offset(in): start offset
 *   size(in): number of bytes
 */
int
lock_region (int fd, int cmd, long offset, long size)
{
  if (lseek (fd, offset, SEEK_SET) != offset)
    {
      return -1;
    }
  return lockf (fd, cmd, size);
}
示例#4
0
int lock_exnb (int fd)
{
  register int r ;
  do
    r = lockf(fd, F_TLOCK, 0) ;
  while ((r == -1) && (errno == EINTR)) ;
  if ((r == -1) && (errno == EACCES)) errno = EAGAIN ;
  return r ;
}
示例#5
0
文件: pipe.c 项目: guker/osnote
int main()
{
	int fd[2];

	char OutPipe[100], InPipe[100];
	pipe(fd);								/* 创建一个管道 */

	while ((p[0] = fork()) == -1);
	if (p[0] == 0)
	{
		printf("p[0]\n");
		lockf(fd[1], 1, 0);					/* 加锁 */
		sprintf(OutPipe, "Child 1 is sending a message!");			/* 把串放入数组outpipe中 */
		write(fd[1], OutPipe, 50);			/* 向管道写长为50字节的串 */
		sleep(1);							/* 自我阻塞1秒 */
		lockf(fd[1], 0, 0);					/* 解锁 */
		exit(0);
	}
	else
	{
		while ((p[1] = fork()) == -1);
		if (p[1] == 0)
		{
			printf("p[1]\n");
			lockf(fd[1], 1, 0);				/* 加锁,互斥 */
			sprintf(OutPipe, "Child 2 is sending a message!");		/* 把串放入数组outpipe中 */
			write(fd[1], OutPipe, 50);		/* 向管道写长为50字节的串 */
			sleep(1);						/* 自我阻塞1秒 */
			lockf(fd[1], 0, 0);				/* 解锁 */
			exit(0);
		}
		else
		{
			printf("parent\n");
			wait(0);						/* 同步 */
			read(fd[0], InPipe, 50);
			printf("%s\n", InPipe);			/* 从管道中读长为50字节的串 */
			wait(0);
			read(fd[0], InPipe, 50);
			printf("%s\n", InPipe);
			exit(0);
		}
	}
}
示例#6
0
int
glusterfs_pidfile_setup (glusterfs_ctx_t *ctx)
{
    cmd_args_t  *cmd_args = NULL;
    int          ret = 0;
    FILE        *pidfp = NULL;

    cmd_args = &ctx->cmd_args;

    if (!cmd_args->pid_file)
        return 0;

    pidfp = fopen (cmd_args->pid_file, "a+");
    if (!pidfp) {
        gf_log ("glusterfsd", GF_LOG_ERROR,
                "pidfile %s error (%s)",
                cmd_args->pid_file, strerror (errno));
        return -1;
    }

    ret = lockf (fileno (pidfp), F_TLOCK, 0);
    if (ret) {
        gf_log ("glusterfsd", GF_LOG_ERROR,
                "pidfile %s lock error (%s)",
                cmd_args->pid_file, strerror (errno));
        return ret;
    }

    gf_log ("glusterfsd", GF_LOG_TRACE,
            "pidfile %s lock acquired",
            cmd_args->pid_file);

    ret = lockf (fileno (pidfp), F_ULOCK, 0);
    if (ret) {
        gf_log ("glusterfsd", GF_LOG_ERROR,
                "pidfile %s unlock error (%s)",
                cmd_args->pid_file, strerror (errno));
        return ret;
    }

    ctx->pidfp = pidfp;

    return 0;
}
示例#7
0
static int
_mas_init_pid( mas_options_t * popts, const char *shash_name )
{
  EVAL_PREPARE;
  int r = 0;

  char *pidpath = NULL;

  r = 0;
  pidpath = mas_strdup( popts->dir.pids );
  pidpath = mas_strcat_x( pidpath, shash_name );

  r = cref( pidpath, popts->dir.pids );
  if ( r == -999 )
    r = cref( pidpath, popts->dir.pids );
  HMSG( "(%d)PIDPATH 1 : %s", r, pidpath );
  if ( r < 0 )
  {
    r = 0;
    IEVAL( r, mas_open( pidpath, O_RDWR | O_EXCL, S_IWUSR | S_IRUSR ) );
  }
  if ( r >= 0 )
  {
    CTRL_PREPARE;

    ctrl.pidfd = r;
    {
      int er = 0;

      IEVALE( r, lockf( ctrl.pidfd, F_TLOCK, 0 ), &er );
      HMSG( "(%d:%d)PIDLCK : %s - %s before", r, errno, pidpath, r < 0 && ( er == EACCES || er == EAGAIN ) ? "LOCKED" : "UNLOCKED" );
    }
    if ( r >= 0 )
    {
      ssize_t lb;
      char buf[64];

      lb = snprintf( buf, sizeof( buf ), "%u", getpid(  ) );
      IEVAL( r, ftruncate( ctrl.pidfd, 0 ) );
      IEVAL( r, write( ctrl.pidfd, buf, lb ) );
      HMSG( "PIDWRT: %d pid:%u W:%ld", r, ctrl.threads.n.main.pid, lb );
      ctrl.pidfilesv.c = mas_add_argv_arg_nodup( ctrl.pidfilesv.c, &ctrl.pidfilesv.v, pidpath );
      pidpath = NULL;
    }
    else
    {
      if ( ctrl.pidfd >= 0 )
        mas_close( ctrl.pidfd );
      ctrl.pidfd = r;
    }
  }
  if ( pidpath )
    mas_free( pidpath );
  HMSG( "(%d)INIT PID", r );
  return r;
}
示例#8
0
文件: daemon.cpp 项目: idaohang/mole
int daemonize()
{

  //#ifdef Q_WS_MAEMO_5
  //  if (daemon(1, 0)) {
  //    qFatal ("Cannot daemonize");
  //  }
  //#else

  if (::getppid() == 1) {
    qWarning ("Already a daemon because owned by init");
    return 0;  // Already a daemon if owned by init
  }

  int i = fork();
  if (i < 0) exit(1); // Fork error
  if (i > 0) exit(0); // Parent exits

  if (::setsid() == -1) { // Create a new process group
    qFatal ("setsid failed");
    return -1;
  }

  (void)chdir("/");
  //#endif

  int lfp = ::open(qPrintable(pidfile), O_RDWR|O_CREAT, 0640);
  if (lfp < 0)
    qFatal("Cannot open pidfile %s\n", qPrintable(pidfile));

  if (lockf(lfp, F_TLOCK, 0) < 0)
    qFatal("Can't get a lock on %s - another instance may be running\n", qPrintable(pidfile));
  QByteArray ba = QByteArray::number(::getpid());
  ::write(lfp, ba.constData(), ba.size());

  //#ifdef Q_WS_MAEMO_5
  // already closed above
  //#else
  int fd;
  if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
    (void)dup2(fd, STDIN_FILENO);
    (void)dup2(fd, STDOUT_FILENO);
    (void)dup2(fd, STDERR_FILENO);
    if (fd > 2)
      (void)close (fd);
  }

  ::signal(SIGCHLD,SIG_IGN);
  ::signal(SIGTSTP,SIG_IGN);
  ::signal(SIGTTOU,SIG_IGN);
  ::signal(SIGTTIN,SIG_IGN);
  //#endif

  return 0;

}
示例#9
0
/* Function responsible with the daemonization procedure */
static void daemonize()
{
	/* file descriptor */
	int l_fp;
	/* container for the pid */
	char l_str[10];
	/* setup a PID and a SID for our HM Daemon */
	pid_t l_al_sid, l_al_pid;

	/* fork process */
	l_al_pid=fork();

	/* test for forking errors */
	if (l_al_pid<0) {
		log_error_message( "Cannot fork off parent process!\n", 0);
		exit(EXIT_FAILURE);
	}

	/* check parent exit */
	if (l_al_pid>0) {
		log_message(stdout, "Parent process exited!\n", 0);
		exit(0);
	}
	/* child (daemon) continues */
	l_al_sid = setsid();
	/* obtain a new process group */
	if (l_al_sid < 0) {
		log_error_message("Cannot set SID for the process!\n", 0);
		exit(EXIT_FAILURE);
	}

	/* set newly created file permissions */
	umask(0);

	l_fp=open(WATCHDOG_PID_FILE, O_RDWR|O_CREAT, 0640);

	/* test if pid file can be open */
	if (l_fp<0) {
		log_error_message("Cannot open pid file\n", 0);
		exit(1);
	}

	/* test if pid file can locked */
	if (lockf(l_fp, F_TLOCK,0)<0) {
		log_error_message("HM Daemon : Cannot obtain lock on pid file\n", 0);
		exit(0);
	}

	/* first instance continues */
	sprintf(l_str, "%d\n", getpid());
	/* record pid to lockfile */
	write(l_fp, l_str, strlen(l_str));

	/* close unneeded file descriptors to maintain security */
	close(STDIN_FILENO);
}
示例#10
0
void fUnlock(int lock) 
{

  if(lock < 0)
    return;

  lockf(lock, F_ULOCK, 0);

  return;
}
示例#11
0
文件: file.c 项目: Feechka/UOBP
static int
modifyRegionLock (int file, int command, off_t length) {
  do {
    if (lockf(file, command, length) != -1) return 1;
  } while (errno == EINTR);

  if (errno == EACCES) errno = EAGAIN;
  if (errno != EAGAIN) logSystemError("lockf");
  return 0;
}
示例#12
0
uint8_t* Blockstorage::getBlock(uint64_t num)
{
	if(!isBlockAvailable(num))
		return NULL;

	int fd = open(_path.c_str(), O_LARGEFILE);

	lseek64(fd, num * BLOCK_SIZE, SEEK_SET);
	lockf(fd, F_LOCK, BLOCK_SIZE);

	uint8_t* block = new uint8_t[BLOCK_SIZE];
	read(fd, block, BLOCK_SIZE);

	lseek64(fd, num * BLOCK_SIZE, SEEK_SET);
	lockf(fd, F_ULOCK, BLOCK_SIZE);
	close(fd);

	return block;
}
示例#13
0
文件: libpr.c 项目: mewaba/mewaba
int f_lock( int fd )
{

    while( lockf(fd, F_TLOCK, 0) == -1 ) {
        if( errno != EAGAIN )
            return -1;
    }
    return 0;

}
示例#14
0
void
gf_store_unlock (gf_store_handle_t *sh)
{
        GF_ASSERT (sh);
        GF_ASSERT (sh->locked == F_LOCK);

        sh->locked = F_ULOCK;
        lockf (sh->fd, F_ULOCK, 0);
        close (sh->fd);
}
示例#15
0
static void get_lock() {
#if !defined(HAVE_LOCKF)
	while (flock(fileno(lockfile_), LOCK_EX) != 0) {
#else
	while (lockf(fileno(lockfile_), F_LOCK, 0) != 0) {
#endif
		history("lockf returned non zero");
	}
//printf("got lock for %d\n", getpid());
}

static void release_lock() {
#if !defined(HAVE_LOCKF)
	flock(fileno(lockfile_), LOCK_UN);
#else
	lockf(fileno(lockfile_), F_ULOCK, 0);
#endif
//printf("released lock for %d\n", getpid());
}
示例#16
0
pidfile::~pidfile()
{
  if(-1 != pidfile_fd)
    {
      // pidfile has been opened and locked
      lockf(pidfile_fd, F_ULOCK, 0);
      close(pidfile_fd);
      unlink(pidfile_path.c_str());
    }
}
示例#17
0
void
flog(int level, char *fmt, ...)
{
	FILE *fp;
	va_list	args;
	int		fd;
	char	timebuf[20];
  char datebuf[20];
	char log_name[100];

	memset( log_name, 0, sizeof( log_name ) ) ;
	memset( datebuf, 0, sizeof( datebuf ) ) ;
	GetDate( datebuf );
	strcpy( log_name, LOG_FILE_NAME ) ;
	strcat( log_name, "." ) ;
	strcat( log_name, datebuf ) ;

	if ((fp = fopen( log_name, "a+" ) ) == NULL)
		return;

	if (level <= LOG_LEVEL) {
    fd = fileno(fp);
    lockf (fd, F_LOCK, 0l);
    GetTime( timebuf );
    fprintf (fp, "%s ", timebuf );
		va_start(args, fmt);
		vfprintf(fp, fmt, args);
		fprintf(fp, "\n");
		/*
		if (level == 0) {
			vfprintf(stderr, fmt, args);
			fprintf(stderr, "\n");
			fflush(stderr);
		}
		*/
		va_end(args);
    lockf(fd, F_ULOCK, 0l);
	}

	fclose(fp);

	return;
}
示例#18
0
bool LockFile::lock()
{
    fd = open(file_name.toUtf8(), O_WRONLY);
    if(fd < -1) {
        perror("open");
        return false;
    }
    // create a file lock
    return(lockf(fd, F_LOCK, 0) == 0);
}
示例#19
0
文件: main.c 项目: Marnie86/storaged
/** 
 * @brief LockProcess
 * 
 * Acquire the process lock (by getting an file lock on our pid file).
 *
 * @param component 
 * 
 * @return true on success, false if failed.
 */
bool LockProcess(const char* component)
{
#define LOCKS_DIR_PATH "/tmp/run"

	pid_t		pid;
	int			fd;
	int			result;
	
	pid = getpid();

	LockFile * lock = &sProcessLock;

	// create the locks directory if necessary
	(void) mkdir(LOCKS_DIR_PATH, 0777);
	
	snprintf(lock->path, sizeof(lock->path), "%s/%s.pid", LOCKS_DIR_PATH, component);
	
	// open or create the lock file
	fd = open(lock->path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
	if (fd < 0)
	{
		g_error("Failed to open lock file (err %d, %s), exiting.", errno, strerror(errno));
		return false;
	}

	// use a POSIX advisory file lock as a mutex
	result = lockf(fd, F_TLOCK, 0);
	if (result < 0)
	{
        if ((errno == EDEADLK) || (errno == EAGAIN))
            g_error("Failed to acquire lock, exiting.");
        else
            g_error("Failed to acquire lock (errno %d, %s), exiting.", errno, strerror(errno));
        
		return false;
	}
	
	// remove the old pid number data
	result = ftruncate(fd, 0);
	if (result < 0)
		g_debug("Failed truncating lock file (err %d, %s).", errno, strerror(errno));
	
	// write the pid to the file to aid debugging
    {
        gchar *pid_str = g_strdup_printf("%d\n", pid);
        int pid_str_len = (int) strlen(pid_str);
        result = write(fd, pid_str, pid_str_len);
        if (result < pid_str_len)
            g_debug("Failed writing lock file (err %d, %s).", errno, strerror(errno));
        g_free(pid_str);
    }
	
	lock->fd = fd;
	return true;
}
示例#20
0
文件: main.cpp 项目: Giermann/ebusd
void daemonize()
{
	// fork off the parent process
	pid_t pid = fork();

	if (pid < 0) {
		logError(lf_main, "fork() failed");
		exit(EXIT_FAILURE);
	}

	// If we got a good PID, then we can exit the parent process
	if (pid > 0)
		exit(EXIT_SUCCESS);

	// At this point we are executing as the child process

	// Create a new SID for the child process and
	// detach the process from the parent (normally a shell)
	if (setsid() < 0) {
		logError(lf_main, "setsid() failed");
		exit(EXIT_FAILURE);
	}

	// Change the current working directory. This prevents the current
	// directory from being locked; hence not being able to remove it.
	if (chdir("/tmp") < 0) {
		logError(lf_main, "daemon chdir() failed");
		exit(EXIT_FAILURE);
	}

	// Close stdin, stdout and stderr
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);

	// create pid file and try to lock it
	pidFile = fopen(PID_FILE_NAME, "w+");

	umask(S_IWGRP | S_IRWXO); // set permissions of newly created files to 750

	if (pidFile != NULL) {
		setbuf(pidFile, NULL); // disable buffering
		if (lockf(fileno(pidFile), F_TLOCK, 0) < 0
			|| fprintf(pidFile, "%d\n", getpid()) <=0) {
			fclose(pidFile);
			pidFile = NULL;
		}
	}
	if (pidFile == NULL) {
		logError(lf_main, "can't open pidfile: " PID_FILE_NAME);
		exit(EXIT_FAILURE);
	}

	isDaemon = true;
}
示例#21
0
    main()
    {
        int fd[3];
        char OutPipe[100], InPipe[100];
        pipe(fd);
        while((pid1=fork())==-1);     
        if (pid1==0)
        {
            printf("p1\n");
            lockf(fd[1],1,0);
            sprintf(OutPipe, "Child 1 process is sending a message!");
            write(fd[1], OutPipe, 50);
            sleep(1);
            lockf(fd[1], 0, 0);
            exit(0);
        }
        else
        {
            while((pid2=fork())==-1);     
            if (pid2==0)
            {
                printf("p2\n");
                lockf(fd[1],1,0);
                sprintf(OutPipe, "Child 2 process is sending a message!");
write(fd[1], OutPipe, 50);
                sleep(1);
                lockf(fd[1], 0, 0);
                exit(0);
            }
            else
            {
                printf("parent\n");
                wait(0);
                read(fd[0], InPipe, 50);
                printf("%s\n", InPipe);
                wait(0);
                read(fd[0], InPipe, 50);
                printf("%s\n", InPipe);
                exit(0);
            }
        }
    }
示例#22
0
void main(int argc, char* argv[])
{
    pid_t pid1, pid2;
    int error;
    int i = 0;

    pid1 = fork();

    if(pid1 < 0){
        fprintf(stderr, "Fork failed");
    }
    else if (pid1 == 0){
        error = lockf(stdout, F_LOCK, 0);
        if (error == 0)
            printf("%#x: lock succeeds!\n", getpid());
        else
            perror("lockf");
 
    
        lockf(stdout, F_ULOCK, 0);
        
        for(i=0;i<10000;i++){
            printf("c");
        }
    }
    else{
        pid2 = fork();
        if(pid2 < 0){
            fprintf(stderr, "Fork failed");        
        }
        else if (pid2 == 0){
            for(i=0;i<10000;i++){
                printf("b");
            }
        }
        else{
            for(i=0;i<10000;i++){
                printf("a");
            }
        }
    }
}
示例#23
0
文件: emq_log.c 项目: skylinelb/emqs
void _emq_app_log(int level, int line, char *filename, const char *fmt, ...){
    if(emqLogSetting == NULL){
        printf("Please Setup Logging first before using the logging function!\n");
        return;
    }
    va_list ap;
    FILE *fp;
    int fd;
    char *c = ".-*#$@";
    char buf[64];
    time_t now;
    struct timeval time1;

    if (level < emqLogSetting->log_level) return;

    fp = (emqLogSetting->log_file_path == NULL) ? stdout : fopen(emqLogSetting->log_file_path,"a");
    if (!fp) { printf("skyline in log file return\n");return; }

    va_start(ap, fmt);
    now = time(NULL);
    memset(buf, 0x00, sizeof(buf));
    strftime(buf,64,"%d %b %H:%M:%S",localtime(&now));
    /*Write to the log file */
    /* lock the file */
    fd = fileno(fp);
    lockf(fd, F_LOCK, 0l);
    fprintf(fp,"[%d] %s %s-%d %c ",(int)getpid(),buf, filename, line, c[level]);
    vfprintf(fp, fmt, ap);
    /* unlock */
    lockf(fd, F_ULOCK, 0l);
    /*Write to the stdout */
    printf("[%d] %s %s-%d %c ",(int)getpid(),buf, filename, line, c[level]);
    va_start(ap, fmt);
    vprintf(fmt, ap);
    printf("\n");
    fprintf(fp, "\n");
    fflush(fp);
    fflush(stdout);
    va_end(ap);

    if (emqLogSetting->log_file_path != NULL) fclose(fp);
}
示例#24
0
static struct alloc_state *alloc_state_load(const char *path)
{
	struct alloc_state *s = xxmalloc(sizeof(*s));
	char statename[CHIRP_PATH_MAX];

	debug(D_ALLOC, "locking %s", path);

	sprintf(statename, "%s/.__alloc", path);

	/* WARNING chirp_alloc assumes we are using the local filesystem */
	s->file = fopen(statename, "r+");
	if(!s->file) {
		free(s);
		return 0;
	}

	if(lockf(fileno(s->file), F_TLOCK, 0)) {
		debug(D_ALLOC, "lock of %s blocked; flushing outstanding locks", path);
		chirp_alloc_flush();
		debug(D_ALLOC, "locking %s (retry)", path);

		if(lockf(fileno(s->file), F_LOCK, 0)) {
			debug(D_ALLOC, "lock of %s failed: %s", path, strerror(errno));
			fclose(s->file);
			free(s);
			return 0;
		}
	}

	fscanf(s->file, "%lld %lld", &s->size, &s->inuse);

	s->dirty = 0;

	if(recovery_in_progress) {
		s->inuse = 0;
		s->dirty = 1;
	}

	s->avail = s->size - s->inuse;

	return s;
}
示例#25
0
int
fixmount_check_mount(char *host, struct in_addr hostaddr, char *path)
{
  FILE *mtab;
  mntent_t *ment;
  int found = 0;

  /* scan mtab for path */
  if (!(mtab = setmntent(_PATH_MTAB, "r"))) {
    perror(_PATH_MTAB);
    exit(1);
  }

  /*
   * setmntent() doesn't do locking in read-only mode. Too bad -- it seems to
   * rely on mount() and friends to do atomic updates by renaming the file.
   * Well, our patched amd rewrites mtab in place to avoid NFS lossage, so
   * better do the locking ourselves.
   */
#ifdef HAVE_FLOCK
  if (flock(fileno(mtab), LOCK_SH) < 0) {
#else /* not HAVE_FLOCK */
  if (lockf(fileno(mtab), F_LOCK, 0) < 0) {
#endif /* not HAVE_FLOCK */
    perror(_PATH_MTAB);
    exit(1);
  }

  while (!found && (ment = getmntent(mtab))) {
    char *colon;

    if ((colon = strchr(ment->mnt_fsname, ':'))) {
      *colon = '\0';
      if ((STREQ(colon + 1, path) ||
	   STREQ(ment->mnt_dir, path)) &&
	  is_same_host(ment->mnt_fsname, host, hostaddr))
	  found = 1;
    }
  }

  (void) endmntent(mtab);

  if (!found) {
    char *swap;

    /* swap files never show up in mtab, only root fs */
    if ((swap = strstr(path, "swap"))) {
      strncpy(swap, "root", 4);	/* this should NOT use xstrlcpy  */
      found = fixmount_check_mount(host, hostaddr, path);
      strncpy(swap, "swap", 4);	/* this should NOT use xstrlcpy  */
    }
  }
  return found;
}
示例#26
0
文件: libpr.c 项目: mewaba/mewaba
int f_unlock( int fd )
{

    while( lockf(fd, F_ULOCK, 0) == -1 ) {
        if( errno == EBADF || errno == ECOMM )
            return -1;
    }

    return 0;

}
示例#27
0
void
xbps_pkgdb_unlock(struct xbps_handle *xhp)
{
	if (pkgdb_fd != -1) {
		if (lockf(pkgdb_fd, F_ULOCK, 0) == -1)
			xbps_dbg_printf(xhp, "[pkgdb] failed to unlock pkgdb: %s\n", strerror(errno));

		(void)close(pkgdb_fd);
		pkgdb_fd = -1;
	}
}
示例#28
0
文件: dm.c 项目: bbidulock/wdm
static int StorePid(void)
{
	int oldpid;

	if (pidFile[0] != '\0') {
		pidFd = open(pidFile, O_RDWR);
		if (pidFd == -1 && errno == ENOENT)
			pidFd = open(pidFile, O_RDWR | O_CREAT, 0666);
		if (pidFd == -1 || !(pidFilePtr = fdopen(pidFd, "r+"))) {
			WDMError("process-id file %s cannot be opened\n", pidFile);
			return -1;
		}
		if (fscanf(pidFilePtr, "%d\n", &oldpid) != 1)
			oldpid = -1;
		fseek(pidFilePtr, 0l, 0);
		if (lockPidFile.i) {
#ifdef F_SETLK
#ifndef SEEK_SET
#define SEEK_SET 0
#endif
			struct flock lock_data;
			lock_data.l_type = F_WRLCK;
			lock_data.l_whence = SEEK_SET;
			lock_data.l_start = lock_data.l_len = 0;
			if (fcntl(pidFd, F_SETLK, &lock_data) == -1) {
				if (errno == EAGAIN)
					return oldpid;
				else
					return -1;
			}
#else
#ifdef LOCK_EX
			if (flock(pidFd, LOCK_EX | LOCK_NB) == -1) {
				if (errno == EWOULDBLOCK)
					return oldpid;
				else
					return -1;
			}
#else
			if (lockf(pidFd, F_TLOCK, 0) == -1) {
				if (errno == EACCES)
					return oldpid;
				else
					return -1;
			}
#endif
#endif
		}
		fprintf(pidFilePtr, "%5ld\n", (long)getpid());
		(void)fflush(pidFilePtr);
		RegisterCloseOnFork(pidFd);
	}
	return 0;
}
示例#29
0
	static lock_file create_or_throw(const int fd){
		const auto lockres = lockf(fd, F_TLOCK, 0);
		if (lockres< 0) {
			const auto err = errno;
			throw std::runtime_error("lockf failed with following error:" + errno_to_string(err));
		}
		lock_file lf;
		lf.fd = fd;
		lf.lockres = lockres;
		return lf;
	}
示例#30
0
void func(void){
	int fd, num,ret;
	FILE *fp = fopen(NAME, "r+");
	if(fp == NULL){
		perror("fopen():");
		exit(-1);
	}
	fd = fileno(fp);
	ret = lockf(fd, F_LOCK, 0);
	if (ret==0) {
		printf("%s\n","one lockf ok");
	}
	ret = lockf(fd, F_LOCK, 0);
	if (ret==0) {
		printf("%s\n", "two lockf ok");
	}
	lockf(fd, F_ULOCK, 0);
	fclose(fp);
	exit(0);
}