Linux 系统运行单例模式

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

#define LOCK_FILE "./App.pid"

int main(void)
{
	char str[20] = {0};
	int fd;

	/*open file*/
	fd = open(LOCK_FILE, O_WRONLY | O_CREAT, 666);
	if(-1 == fd){
		perror("open error");
		exit(-1);	
	}
	
	/*noblock*/
	if(-1 == flock(fd, LOCK_EX | LOCK_NB)){
		fputs("not run app!\n",stderr);
		exit(-1);	
	}

	puts("running......");

	ftruncate(fd, 0);
	sprintf(str, "%d\n", getpid());
	write(fd, str, strlen(str));

	for(;;)
	sleep(1);

	exit(0);

}

你可能感兴趣的:(Linux,linux)