linux c root执行某个程序,不能重复执行

linux c root 执行某个程序,不能重复执行

参考 :
biometric-authenticationd.c

保证root
执行是 getuid = 0

保证不重复执行
是 写一个 /tmp/biometric-authentication.pid

里面是一个数字,这个数字是通过gitpid得到的,当前进程的pid号码。

int main()
{
	int i = 0;
	int ret = 0;
	int uid = getuid();
	int pid = getpid();
	char * pid_dir_list[PID_DIR_NUM] = {PID_DIR_0, PID_DIR_1};
	char * pid_dir = NULL;
	char pid_file[MAX_PATH_LEN] = {0};
	char pid_string[MAX_PID_STRING_LEN] = {0};

	if (uid != 0)
	{
		bio_print_error(_("The biometric authentication server failed to start, "
						  "requiring administrator permission to start\n"));
		return -1;
	}

	for (i = 0; i < PID_DIR_NUM; i++)
	{
		struct stat dir_stat;

        if (access(pid_dir_list[i], F_OK) == 0) {
            stat(pid_dir_list[i], &dir_stat);
            if (S_ISDIR(dir_stat.st_mode)) {
                pid_dir = pid_dir_list[i];
                break;
            }
        }
	}
	if (pid_dir == NULL)
		pid_dir = "/";

	snprintf(pid_file, MAX_PATH_LEN, "%s/%s.pid", pid_dir, AUTH_SERVER_NAME);
	int pid_file_fd = open(pid_file, O_CREAT | O_TRUNC | O_RDWR, 0644);
	if (pid_file_fd < 0)
	{
		bio_print_error(_("Can not open PID file: %s\n"), pid_file);
		return -1;
	}

	ret = flock(pid_file_fd, LOCK_EX | LOCK_NB);
	if (ret < 0)
	{
		bio_print_error(_("Biometric authentication server is running, "
						  "Do not restart it repeatedly\n"));
		return -1;
	}
		snprintf(pid_string, MAX_PID_STRING_LEN, "%d\n", pid);
	ret = write(pid_file_fd, pid_string, strlen(pid_string));
	if (ret != strlen(pid_string))
	{
		bio_print_warning(_("There is an exception to write PID file: %s\n"),
						  pid_file);
	}

	.......

	flock(pid_file_fd, LOCK_UN);
	close(pid_file_fd);	
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值