linux 平台简单防止进程多开编程

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define DAEMON_FILE_PID  "/var/run/daemon.pid"

int main(int argc, char** argv)
{
	int fd;
	int ret;
	struct flock lock = {
		.l_type = F_WRLCK,
		.l_whence = SEEK_SET,
		.l_start = 0,
		.l_len = 0
	};
	char buff[32] = {0};
	sprintf(buff, "%d\n", getpid());
	
	fd = open(DAEMON_FILE_PID, O_RDWR | O_CREAT);
	if (fd < 0) {
		perror("failed to open file");
		return -1;
	}
	
	memset(&lock, 0, sizeof(lock));
	ret = fcntl(fd, F_GETLK, &lock);
	if (ret < 0) {
		perror("failed to get file lock info");
		return -1;
	}
	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;
	ret = fcntl(fd, F_SETLK, &lock);
	if (ret < 0) {
		perror("failed to lock pid");
		return -1;
	}
	ret = write(fd, buff, strlen(buff));
	if (ret < 0) {
		perror("failed to write pid");
		return -1;
	}
	
	printf("lock file success...\r\n");
	ret = getchar();
	return 0;
}

你可能感兴趣的:(c++,linux,算法,运维)