Example #1
0
static void
lockabyte(const char *name, int fd, off_t offset)
{
    if (writew_lock(fd, offset, SEEK_SET, 1) < 0)   /* Figure-14.5.c */
        err_sys("%s: writew_lock error", name);
    printf("%s: got the lock, byte %lld\n", name, (long long)offset);
}
Example #2
0
static void lockabyte(const char *name, int fd, off_t offset)
{
    if (writew_lock(fd, offset, SEEK_SET, 1) < 0)
        err_sys("%s: writew_lock error", name);

    printf("%s: got the lock, byte %ld\n", name, offset);
}
/* writing an index record
_db_writedat() is called before this function inorder to set fields datoff and datlen in the database structure where we gotta write index record */
void _db_writeidx(DB *db, const char *key, off_t offset, int whence, off_t ptrval)
{
	struct iovec iov[2];
	char asciiptrlen[PTR_SZ + IDXLEN_SZ + 1];
	int len;
	if((db->ptrval = ptrval) < 0 || ptrval > PTR_MAX)
		err_quit("invalid ptr: %d", ptrval);
	sprintf(db->idxbuf, "%s%c%d%c%d\n", key, SEP, db->datoff, SEP, db->datlen);
	if((len = strlen(sb->idxbuf)) < IDXLEN_MIN || len > IDXLEN_MAX)
		err_dump("invalid length");
	sprintf(asciiptrlen, "%*d%*d", PTR_SZ, ptrval, IDXLEN_SZ, len);
	/* If we are appending, then we gotta lock before doing lseek() and write() in making the two as atomic operation.
	If we are overwriting an existing record, then we don't have to lock */
	if(whence == SEEK_END) /* we are appending, then lock the entire file. */
		if(writew_lock(db->idxfd, 0, SEEK_SET, 0) < 0)
			err_dump("error");
	if((db->idxoff = lseek(db->idxfd, offset, whence)) == -1)
		err_dump("error");
	iov[0].iov_base = asciiptrlen;
	iov[0].iov_len = PTR_SZ + IDXLEN_SZ;
	iov[1].iov_base = db->idxbuf;
	iov[1].iov_len = len;
	if(writev(db->idxfd, &iov[0], 2) != PTR_SZ + IDXLEN_SZ + len)
		err_dump("error");
	if(whence == SEEK_END)
		if(un_lock(db->idxfd, ((db->nhash + 1)*PTR_SZ)+1, SEEK_SET, 0) < 0)
			err_dump("error");
}
/* Find specified record.
Called by db_delete(), db_fetch() and db_store() */
int _db_find(DB *db, const char *key, int writelock)
{
    off_t offset, nextoffset;
    /* calculate hash value for this key, then calculate byte offset of corresponding chain ptr in hash table.
    */
    /* calculate offset in hash table for this key */
    db->chainoff = (_db_hash(db, key) * PTR_SZ) + db->hashoff;
    db->ptroff = db->chainoff;
    /* here's where we lock this hash chain. It's the caller responsibility to unlock it when done.
    Note that we lock and unlock only the first byte. */
    if(writelock)
    {
        if(writew_lock(db->idxfd, db->chainoff, SEEK_SET, 1) < 0)
            err_dump("error");
    }
    else
    {
        if(readw_lock(db->idxfd, db->chainoff, SEEK_SET, 1) < 0)
            err_dump("error");
    }
    /* Get the offset in the index file of first record on the bash chain (it can be 0 too) */
    offset = _db_readptr(db, db->ptroff);
    while(offset!=0)
    {
        nextoffset = _db_readidx(db, offset);
        if(strcmp(db->idxbuf, key) == 0)
            break; /* found a match */
        db->ptroff = offset; /* offset of this (unequal) record */
        offset = nextoffset; /* next one to compare */
    }
    if(offset == 0)
        return(-1); /* error -- record not found */
    return(0); /* if not error */
}
Example #5
0
 void FileLocks::lock( size_t lock_pos )
 {
     check_thread_lock( lock_pos );
     //std::cout << lock sizeof m_pmutexs_ = " << m_pmutexs_.size() << std::endl;
     m_pmutexs_[lock_pos]->lock();
     writew_lock( m_fd_, lock_pos + 4, SEEK_SET, 1 );
 }
Example #6
0
enum RECORD_RESULT record_write(struct record_t *record, const char *content, size_t size)
{
    if (NULL == record) {
        fprintf (stderr, "Invalid record in record_flush\n");
        return RECORD_ERROR;
    }

    record_open(record);

    writew_lock(record->fd, 0, SEEK_SET, 0);
    lseek(record->fd, 0, SEEK_END);

    int ret = write(record->fd, content, size);

    un_lock(record->fd, 0, SEEK_SET, 0);

    record_close(record);

    if (-1 == ret) {
        fprintf (stderr, "record_write failed\n");
        return RECORD_ERROR;
    }

    if (debug) fprintf (stderr, "record_write: %s %s\n", record->filename, content);
    return RECORD_SUCCESS;
}
Example #7
0
File: miscd.c Project: wyat/kbs
int killdir(char *basedir, char *filename)
{
    int fd;
    struct stat st;
    struct fileheader *files, *afile;
    int i;
    int now = (time(NULL) / 86400) % 100;
    int count = 0;
    int deleted = 0;

    strcpy(genbuf1, basedir);
    strcat(genbuf1, "/");
    strcat(genbuf1, filename);
    fd = open(genbuf1, O_RDWR);
    if (fd < 0)
        return 0;
    if (writew_lock(fd, 0, SEEK_SET, 0) < 0) {
        close(fd);
        return 0;
    }
    if (fstat(fd, &st) < 0) {
        un_lock(fd, 0, SEEK_SET, 0);
        close(fd);
        return 0;
    }
    if ((files = (struct fileheader *) malloc(st.st_size)) == NULL) {
        un_lock(fd, 0, SEEK_SET, 0);
        close(fd);
        return 0;
    }
    if (read(fd, files, st.st_size) < 0) {
        free(files);
        un_lock(fd, 0, SEEK_SET, 0);
        close(fd);
        return 0;
    }
    lseek(fd, 0, 0);
    for (i = 0, afile = files; i < st.st_size / sizeof(struct fileheader); i++, afile++) {
    int delta;
    delta=now-afile->accessed[sizeof(afile->accessed) - 1];
    if (delta<0) delta+=100;
        if (delta > DAY_DELETED_CLEAN) {
            strcpy(genbuf1, basedir);
            strcat(genbuf1, "/");
            strcat(genbuf1, afile->filename);
            unlink(genbuf1);
            deleted++;
        } else {
            write(fd, afile, sizeof(struct fileheader));
            count += sizeof(struct fileheader);
        }
    }
    ftruncate(fd, count);
    /*flock(fd, LOCK_EX);*/ /* 又写错了 .. ? */
    un_lock(fd, 0, SEEK_SET, 0);
    free(files);
    close(fd);
    return deleted;
}
/* Opening or Creating a database */
DB *db_open(const char *pathname, int oflag, int mode)
{
	DB *db;
	int i, len;
	char asciiptr[PTR_SZ + 1], hash[(NHASH_DEF + 1) * PTR_SZ +2]; /* +2 for newline and NULL */
	struct stat statbuff;
	/* Allocating a Database structure and the buffer it requires. */
	len = strlen(pathname);
	if((db = _db_alloc(len)) == NULL)
		err_dump("error");
	db->oflag = oflag; /* saving a copy of the open flags */
	/* Opening index file */
	strcpy(db->name, pathname);
	strcat(db->name, ".idx");
	if((db->idxfd = open(db->name, oflag, mode)) < 0)
	{
		_db_free(db);
		return(NULL);
	}
	/* Opening data file */
	strcpy(db->name + len, ".dat");
	if((db->datfd = open(db->name, oflag, mode)) < 0)
	{
		_db_free(db);
		return(NULL);
	}
	/* If the database was created, then initialize it */
	if((oflag & (O_CREAT | O_TRUNC)) == (O_CREAT | O_TRUNC))
	{
		/* write lock the entire file and so that, we can stat the file, check it's size & initialize it */
		if(writew_lock(db->idxfd, 0, SEEK_SET, 0) < 0)
			err_dump("error");
		if(fstat(db->idxfd, &statbuff) < 0)
			err_sys("error");
		if(statbuff.st_size==0)
		{
			/* 
			We gotta build a list of (NHASH_DEF + 1) chain ptr with a value of 0.
			The +1 is for free list pointer that precedes the hash table.
			*/
			sprintf(asciiptr, "%*d", PTR_SZ, 0);
			hash[0] = 0;
			for(i=0;i<(NHASH_DEF + 1);i++)
				strcat(hash, asciiptr);
			strcat(hash, "\n");
			i = strlen(hash);
			if(write(db->idxfd, hash, i) != i)
				err_dump("error");
		}
		if(un_lock(db->idxfd, 0, SEEK_SET, 0) < 0)
			err_dump("error");
	}
	db->nhash = NHASH_DEF; /* hash table size */
	db->hashoff = HASH_OFF; /* offset in index file of hash table */
							/* free list ptr always at FREE_OFF */
	db_rewind(db);
	return(db);
}
Example #9
0
        bool FileLocks::timed_lock( size_t lock_pos, int wait_sec )
        {
            check_thread_lock( lock_pos );
            int loops = wait_sec * 50;
            while ( loops-- )
            {
                if ( m_pmutexs_[lock_pos]->try_lock() )
                {
                    while ( loops-- )
                    {
                        if ( write_lock( m_fd_, lock_pos + 4, SEEK_SET, 1 ) != -1 ) return true;
                        boost::this_thread::sleep( boost::posix_time::milliseconds( 20 ) );
                    }
                    m_pmutexs_[lock_pos]->unlock();
                    return false;
                }
                boost::this_thread::sleep( boost::posix_time::seconds( 20 ) );
            }

            return false;

#if 0
            if ( m_thread_mutex_.try_lock() )
            {
                lock( lock_pos );
                return true;
            }
            else
            {
                bool ret = false;
                struct sigaction act, oact;

                act.sa_handler = nullhander;
                sigemptyset( &act.sa_mask );
                act.sa_flags = 0;
                sigaction( SIGALRM, &act, &oact );
                int sec = alarm( wait_sec );
                if ( writew_lock( m_fd_, lock_pos + 4, SEEK_SET, 1 ) == 0 )
                {
                    alarm( sec );
                    sigaction( SIGALRM, &oact, NULL );
                    ret = true;
                }
                else
                {
                    alarm( sec );
                    sigaction( SIGALRM, &oact, NULL );
                    ret = false;
                }

                return ret;
            }
#endif

        }
Example #10
0
static int bcache_lock()
{
    int lockfd;
    char errbuf[STRLEN];
    lockfd = creat("bcache.lock", 0600);
    if (lockfd < 0) {
        bbslog("3system", "CACHE:lock bcache:%s", strerror_r(errno, errbuf, STRLEN));
        return -1;
    }
    bcache_setreadonly(0);
    writew_lock(lockfd, 0, SEEK_SET, 0);
    return lockfd;
}
Example #11
0
void print_msgs(const char *name, int fd) {

	int i;
	for (i = 0; i < 200; i++) {
		if (writew_lock(fd, 0, SEEK_SET, 0) < 0) {
			perror("Unable to acquire lock");
			return;
		}

		write(fd, name, strlen(name));
		write(fd, buf, sizeof(buf)-1);

		un_lock(fd, 0, SEEK_SET, 0);
	}

}
Example #12
0
File: utmp.c Project: wyat/kbs
int utmp_lock()
{
    int utmpfd = 0;

    utmpfd = open(ULIST, O_RDWR | O_CREAT, 0600);
    if (utmpfd < 0) {
        exit(-1);
    }
    signal(SIGALRM, longlock);
    alarm(10);
    if (writew_lock(utmpfd, 0, SEEK_SET, 0) == -1) {
        exit(-1);
    }
    signal(SIGALRM, SIG_IGN);
    return utmpfd;
}
Example #13
0
File: qmail2bbs.c Project: wyat/kbs
int my_after_post(struct fileheader *fh, char *boardname)
{
	char buf[256];
	int fd, err = 0, nowid = 0;

	if (!strncmp(fh->title, "Re:", 3)) {
		strncpy(fh->title, fh->title + 4, STRLEN);
	}
	setbfile(buf, boardname, DOT_DIR);

	if ((fd = open(buf, O_WRONLY | O_CREAT, 0664)) == -1) {
		err = 1;
	}

	if (!err) {
        writew_lock(fd, 0, SEEK_SET, 0);
		nowid = get_nextid(boardname);
		fh->id = nowid;
		fh->groupid = fh->id;
		fh->reid = fh->id;
#ifdef HAVE_REPLY_COUNT
		fh->replycount = 1;
#endif /* HAVE_REPLY_COUNT */
		set_posttime(fh);
		lseek(fd, 0, SEEK_END);
		if (safewrite(fd, fh, sizeof(fileheader)) == -1) {
			err = 1;
		}
        un_lock(fd, 0, SEEK_SET, 0);
		close(fd);
	}
	if (err) {
		setbfile(buf, boardname, fh->filename);
		unlink(buf);
		return 1;
	}
	updatelastpost(boardname);

	if (fh->id == fh->groupid)
		setboardorigin(boardname, 1);
	setboardtitle(boardname, 1);
	return 0;
}
/* Writing a data record and called by _db_dodelete() and db_store() */
void _db_writedat(DB *db, const char *data, off_t offset, int whence)
{
	struct iovec iov[2];
	static char newline = '\n';
	/* If we are appending, then we gotta lock before doing lseek() and write() in making the two as atomic operation.
	If we are overwriting an existing record, then we don't have to lock */
	if(whence == SEEK_END) /* we are appending, then lock the entire file. */
		if(writew_lock(db->datfd, 0, SEEK_SET, 0) < 0)
			err_dump("error");
	if((db->datoff = lseek(db->datfd, offset, whence)) == -1)
		err_dump("error");
	db->datlen = strlen(data) + 1; /* datlen includes newline */
	iov[0].iov_base = (char *) data;
	iov[0].iov_len = db->datlen - 1;
	iov[1].iov_base = &newline;
	iov[1].iov_len = 1;
	if(writev(db->datfd, &iov[0], 2) != db->datlen)
		err_dump("error");
	if(whence == SEEK_END)
		if(un_lock(db->datfd, 0, SEEK_SET, 0) < 0)
			err_dump("error");
}
/* Try to find a free index record and accompany data record of correct sizes.
We're only called by db_store() */
int _db_findtree(DB *db, int keylen, int datalen)
{
	int rc;
	off_t offset, nextoffset, saveoffset;
	/* locking the free list */
	if(writew_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
		err_dump("error");
	/* reading the free list pointer */
	saveoffset = FREE_OFF;
	offset = _db_readptr(db, saveoffset);
	while(offset != 0)
	{
		nextoffset = _db_readidx(db, offset);
		if(strlen(db->idxbuf) == keylen && db->datlen == datlen)
			break; /* found a match */
		saveoffset = offset;
		offset = nextoffset;
	}
	if(offset == 0)
		rc = -1; /* no match found */
	else
	{
		/* Found a tree record with matching sizes.
			The index record was read in by _db_readidx() above which sets db->ptrval.
			Also, saveoffset points to the chain ptr that pointed to empty record on free list.
			We'll be setting this chain ptr to db->ptrval, which removes empty record from free list
			*/
		_db_writeptr(db, saveoffset, db->ptrval);
		rc = 0;
		/* _db_readidx() set both db->idxoff and db->datoff.
			This is used by the caller, db_store() inorder to write new index record and data record
		*/
	}
	/* Unlocking the free list */
	if(un_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
		err_dump("error");
	return(rc);
}
Example #16
0
static void flushlog(int signo)
{
    int i;
    for (i = 0; i < sizeof(logconfig) / sizeof(struct taglogconfig); i++) {
        struct taglogconfig *pconf;

        pconf = &logconfig[i];
        if (pconf->fd>=0 && pconf->buf && pconf->bufptr) {
            writew_lock(pconf->fd, 0, SEEK_SET, 0);
            lseek(pconf->fd, 0, SEEK_END);
            write(pconf->fd, pconf->buf, pconf->bufptr);
            pconf->bufptr = 0;
            un_lock(pconf->fd, 0, SEEK_SET, 0);
        }
        if (signo!=-1)
            close(pconf->fd);
    }
    if (signo==-1) return;
#if defined(NEWPOSTLOG) || defined(NEWBMLOG)
	closenewpostlog();
#endif
    exit(0);
}
/* Deleting the current record specified by the database structure.
This function is called by db_delete() and db_store() after the record has been located by _db_find() */
int _db_dodelete(DB *db)
{
	int i;
	char *ptr;
	off_t freeptr, saveptr;
	/* Setting data buffer to all blanks */
	for(ptr = db->datbuf, i = 0; i < db->datlen - 1; i++)
		*ptr++ = ' ';
	*ptr = 0; /*null terminate for _db_writedat()*/
	/* Setting key to blanks */
	ptr = db->idxbuf;
	while(*ptr)
		*ptr++ = ' ';
	/* Locking the free list */
	if(writew_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
		err_dump("error");
	/* Writing the data record with all blanks */
	_db_writedat(db, db->datbuf, db->datoff, SEEK_SET);
	/* Reading the free list pointer.
	It's value becomes the chain ptr field of the deleted index record.
	This means that the deleted  record becomes the head of the free list. */
	freeptr = _db_readptr(db, FREE_OFF);
	/* Save the contents of the index record chain ptr before being re-written by _db_writeidx() */
	saveptr = db->ptrval;
	/* Re-writing the index record, which also re-writes the length of the index record , data offset & data length*/
	_db_writeidx(db, db->idxbuf, db->idxoff, SEEK_SET, freeptr);
	/* Writing the new free list pointer */
	_db_writeptr(db, FREE_OFF, db->idxoff);
	/* Re-writing the chain ptr that pointed to this record being deleted.
	Recalling that _db_find() sets db->ptroff to point to this chain ptr.
	We'll be setting this chain ptr to the contents of the deleted record's chain ptr, saveptr, which can be either zero or not */
	_db_writeptr(db, db->ptroff, saveptr);
	if(un_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
		err_dump("error");
	return(0);
}
Example #18
0
int main(void)
{
	int		fd;
	int		i, counter;
	void	*area;
	pid_t	pid;

	/*
	 * anonymous memory map for related processes
	 */
	if((area = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED,
			-1, 0)) == MAP_FAILED)
		err_sys("mmap error");

	/* create lock file, such as TELL_WAIT() */
	if ((fd = open("templock", O_RDWR | O_CREAT | O_TRUNC, FILE_MODE)) < 0)
		err_sys("open error");
	if (write(fd, "lock", 4) < 0)
		err_sys("write error");

	/* gets write lock */
	if (writew_lock(fd, 0, SEEK_SET, 0) < 0)
		err_sys("write_lock error");

	if((pid = fork()) < 0)
	{
		err_sys("fork error");
	}
	else if(pid > 0)		/* parent */
	{
		for(i = 0; i < NLOOPS; i += 2)
		{
			if((counter = update((long *)area)) != i)
				err_quit("parent: expected %d, got %d", i, counter);
			printf("parent: counter %d, area %ld\n", counter, *(long *)area);

			if (un_lock(fd, 0, SEEK_SET, 0) < 0)
				err_sys("un_lock error");

			sleep(1);	/* to have child get the lock */

			/* gets write lock */
			if (writew_lock(fd, 0, SEEK_SET, 0) < 0)
				err_sys("writew_lock error");
		}
	}
	else					/* child */
	{
		for(i = 1; i < NLOOPS + 1; i += 2)
		{
			/* gets write lock */
			if (writew_lock(fd, 0, SEEK_SET, 0) < 0)
				err_sys("writew_lock error");

			if((counter = update((long *)area)) != i)
				err_quit("child: expected %d, got %d", i, counter);
			printf("child: counter %d, area %ld\n", counter, *(long *)area);

			if (un_lock(fd, 0, SEEK_SET, 0) < 0)
				err_sys("un_lock error");

			sleep(1);	/* to have parent get the lock */
		}
	}

	return 0;
}
Example #19
0
int main(int argc, char **argv)
{
    FILE* fin,*fout1,*fout2;
	char genbuf[8][256];
	char* ptr;
	int i;
	struct userec * uc;
	int now;
    int exit = 0,goonsearch = 1;
	char userid[IDLEN+2];

	chdir(BBSHOME);
	
	resolve_ucache();
	resolve_utmp();

    now = time(NULL);
	if((fin = fopen("pre_register","r+")) == NULL)
	{
	    printf("open pre_register file failed.\n");
	    return 0;
	}
	if((fout1 = fopen("pre_register1","w")) == NULL)
	{
	    fclose(fin);
	    printf("open pre_register1 file failed.\n");
	    return 0;
	}
	if((fout2 = fopen("new_register","a")) == NULL)
	{
	    fclose(fin);
		fclose(fout1);
	    printf("open pre_register file failed.\n");
	    return 0;
	}

    writew_lock(fileno(fin), 0, SEEK_SET, 0);
	while(!exit){
	    for(i = 0; i < 8;i++)
		{
            if(fgets(genbuf[i], 256, fin) == NULL){
			    exit = 1;
			    break;
			}
		}
		if(exit == 1)break;
		if(goonsearch){
			strncpy(userid,genbuf[1]+8,IDLEN);
			if((ptr=strchr(userid,'\n')) != NULL)*ptr = 0;
			userid[IDLEN]=0;
			if(getuser(userid,&uc) == 0)
			{
		    	printf("genbuf[1] is %s",genbuf[1]);
		    	printf("%s not found\n",userid);
		    	continue;  //get userid's userec
			}
			if((now - uc->firstlogin) > REGISTER_WAIT_TIME)
			{
            		for(i = 0; i < 8;i++)fputs(genbuf[i],fout2);
			}
			else{
				goonsearch=0;
            			for(i = 0; i < 8;i++)fputs(genbuf[i],fout1);
			}
		}else{
			for(i = 0;i< 8; i++)fputs(genbuf[i],fout1);
		}
    }
//    rewind(fout1);
//    ftruncate(fileno(fin),0);
//    while(fgets(genbuf[0],256,fout1))
//    	fputs(genbuf[0],fin);
    un_lock(fileno(fin), 0, SEEK_SET, 0);
    fclose(fin);
    fclose(fout1);
    fclose(fout2);
	
	f_mv("pre_register1","pre_register");
}
Example #20
0
static void writelog(struct bbs_msgbuf *msg)
{
    char header[256];
    struct tm *n;
    struct taglogconfig *pconf;
    char ch;

#if defined(NEWPOSTLOG) || defined(NEWBMLOG)
	if(!postlog_start && mysqlclosetime && time(0)-mysqlclosetime>600)
		opennewpostlog();
#endif

#ifdef NEWBMLOG
	if (msg->mtype == BBSLOG_BM){
		char sqlbuf[512];
		struct _new_bmlog * ppl = (struct _new_bmlog *)( &msg->mtext[1]) ;
		int affect;

		if(!postlog_start)
			return;

		if(ppl->value == 0)
			return;

		msg->mtext[0]=0;

		sprintf(sqlbuf, "UPDATE bmlog SET `log%d`=`log%d`+%d WHERE userid='%s' AND bname='%s' AND month=MONTH(CURDATE()) AND year=YEAR(CURDATE()) ;", ppl->type, ppl->type, ppl->value, msg->userid, ppl->boardname );

		if( mysql_real_query(&s,sqlbuf,strlen(sqlbuf)) || (affect=(int)mysql_affected_rows(&s))<0 ){
			mysql_fail ++;
			bbslog("3system","mysql bmlog error:%s",mysql_error(&s));
			if(mysql_fail > 10)
				closenewpostlog();
			return;
		}

		if(affect <= 0){
			sprintf(sqlbuf, "INSERT INTO bmlog (`id`, `userid`, `bname`, `month`, `year`, `log%d` ) VALUES (NULL, '%s', '%s', MONTH(CURDATE()), YEAR(CURDATE()), '%d' );", ppl->type, msg->userid, ppl->boardname, ppl->value);

			if( mysql_real_query( &s, sqlbuf, strlen(sqlbuf) )){
				mysql_fail ++;
				bbslog("3system","mysql bmlog error:%s",mysql_error(&s));
				if(mysql_fail > 10)
					closenewpostlog();
			}else
				mysql_fail = 0;
		}else{
			mysql_fail = 0;
		}

		return;
	}
#endif

#ifdef NEWPOSTLOG
	if (msg->mtype == BBSLOG_POST && postlog_start){

		char newtitle[161];
		char sqlbuf[512];
		struct _new_postlog * ppl = (struct _new_postlog *) ( &msg->mtext[1]) ;
		char newts[20];

		msg->mtext[0]=0;

		mysql_escape_string(newtitle, ppl->title, strlen(ppl->title));

#ifdef NEWSMTH
		sprintf(sqlbuf, "INSERT INTO postlog (`id`, `userid`, `bname`, `title`, `time`, `threadid`, `articleid`, `ip`) VALUES (NULL, '%s', '%s', '%s', '%s', '%d', '%d', '%s');", msg->userid, ppl->boardname, newtitle, tt2timestamp(msg->msgtime, newts), ppl->threadid, ppl->articleid, ppl->ip );
#else
		sprintf(sqlbuf, "INSERT INTO postlog (`id`, `userid`, `bname`, `title`, `time`, `threadid`, `articleid`) VALUES (NULL, '%s', '%s', '%s', '%s', '%d', '%d');", msg->userid, ppl->boardname, newtitle, tt2timestamp(msg->msgtime, newts), ppl->threadid, ppl->articleid );
#endif

		if( mysql_real_query( &s, sqlbuf, strlen(sqlbuf) )){
			mysql_fail ++;
			bbslog("3system","mysql postlog error:%s",mysql_error(&s));
			if(mysql_fail > 10)
				closenewpostlog();
		}else{
			mysql_fail = 0;

			return;
		}
	}

	if (msg->mtype == BBSLOG_POST){
		struct _new_postlog * ppl = (struct _new_postlog *) ( &msg->mtext[1]) ;

		msg->mtype = BBSLOG_USER;

    	if ((msg->mtype < 0) || (msg->mtype > sizeof(logconfig) / sizeof(struct taglogconfig)))
        	return;
    	pconf = &logconfig[msg->mtype-1];

    	if (pconf->fd<0) return;
    	n = localtime(&msg->msgtime);

    	snprintf(header, 256, "[%02u/%02u %02u:%02u:%02u %5lu %lu] %s post '%s' on '%s'\n", n->tm_mon + 1, n->tm_mday, n->tm_hour, n->tm_min, n->tm_sec, (long int) msg->pid, msg->mtype, msg->userid, ppl->title, ppl->boardname);
    	if (pconf->buf) {
        	if ((int) (pconf->bufptr + strlen(header)) <= pconf->bufsize) {
            	strcpy(&pconf->buf[pconf->bufptr], header);
            	pconf->bufptr += strlen(header);
            	return;
        	}
    	}

/*目前log还是分散的,就先lock,seek吧*/
        writew_lock(pconf->fd, 0, SEEK_SET, 0);
    	lseek(pconf->fd, 0, SEEK_END);

    	if (pconf->buf && pconf->bufptr) {
        	write(pconf->fd, pconf->buf, pconf->bufptr);
        	pconf->bufptr = 0;
    	}
        un_lock(pconf->fd, 0, SEEK_SET, 0);

		return;
	}

#endif

    if ((msg->mtype < 0) || (msg->mtype > sizeof(logconfig) / sizeof(struct taglogconfig)))
        return;
    pconf = &logconfig[msg->mtype-1];

    if (pconf->fd<0) return;
    n = localtime(&msg->msgtime);

    ch=msg->mtext[0];
    msg->mtext[0]=0;
    snprintf(header, 256, "[%d-%02u-%02u %02u:%02u:%02u %5lu %lu] %s %c%s", n->tm_year + 1900, n->tm_mon + 1, n->tm_mday, n->tm_hour, n->tm_min, n->tm_sec, (long int) msg->pid, msg->mtype, msg->userid,ch,&msg->mtext[1]);
    if (pconf->buf) {
        if ((int) (pconf->bufptr + strlen(header)) <= pconf->bufsize) {
            strcpy(&pconf->buf[pconf->bufptr], header);
            pconf->bufptr += strlen(header);
            return;
        }
    }

/*目前log还是分散的,就先lock,seek吧*/
    writew_lock(pconf->fd, 0, SEEK_SET, 0);
    lseek(pconf->fd, 0, SEEK_END);

    if (pconf->buf && pconf->bufptr) {
        write(pconf->fd, pconf->buf, pconf->bufptr);
        pconf->bufptr = 0;
    }
    un_lock(pconf->fd, 0, SEEK_SET, 0);
}
Example #21
0
        size_t FileLocks::alloc_lock( std::string const & keyname )
        {
            if ( keyname.empty() )
            {
                m_thread_mutex_.lock();

                writew_lock( m_fd_, 0, SEEK_SET, 4 );

                char buff[4 + 1] = { 0 };
                long seqno = 0;
                size_t readlen = 0;
                lseek( m_fd_, 0L, SEEK_SET );
                readlen = read( m_fd_, buff, 4 );
                buff[readlen] = '\0';
                readlen = sscanf( buff, "%ld", &seqno );
                snprintf( buff, sizeof( buff ), "%ld", seqno + 1 );
                lseek( m_fd_, 0L, SEEK_SET );
                write( m_fd_, buff, strlen( buff ) );

                un_lock( m_fd_, 0, SEEK_SET, 4 );

                m_pmutexs_.resize( seqno + 1 );
                m_pmutexs_[seqno] = new boost::mutex;
                //std::cout << alloc_lock id = "  << seqno << " lock addr = " << m_pmutexs_[seqno] << " this = " << this << std::endl;
                m_thread_mutex_.unlock();

                return seqno;
            }
            else/// 命名锁
            {
                m_thread_mutex_.lock();
                writew_lock( m_fd_, 0, SEEK_SET, 4 );

                /// 载入已有的锁
                std::ifstream ifs;
                ifs.open( namelock_cache( "process.filelock" ).string().c_str() );
                std::string line;
                std::getline(ifs, line);
                while (std::getline(ifs, line)) 
                {
                    if (line.empty() || line[0] == '#')
                    {
                        continue;
                    }
                    std::string::size_type p = line.find('\t');
                    if (p == std::string::npos)
                    {
                        continue;
                    }

                    std::string name = line.substr(0, p);
                    long value = atol( line.substr(p + 1).c_str() );
                    if ( name == keyname )
                    {
                        ifs.close();
                        un_lock( m_fd_, 0, SEEK_SET, 4 );
                        m_thread_mutex_.unlock();
                        return value;
                    }
                }
                ifs.close();

                // 没有查到
                char buff[4 + 2] = { 0 };
                long seqno = 0;
                size_t readlen = 0;
                lseek( m_fd_, 0L, SEEK_SET );
                readlen = read( m_fd_, buff, 4 );
                buff[readlen] = '\0';
                readlen = sscanf( buff, "%ld", &seqno );
                snprintf( buff, sizeof( buff ), "%ld\n", seqno + 1 );
                lseek( m_fd_, 0L, SEEK_SET );
                write( m_fd_, buff, strlen( buff ) );

                /// 附加到尾部
                std::ofstream ofs;
                ofs.open( namelock_cache( "process.filelock" ).string().c_str(), std::ios_base::app );
                ofs << keyname << "\t" << seqno << std::endl;
                ofs.close();

                un_lock( m_fd_, 0, SEEK_SET, 4 );

                m_pmutexs_.resize( seqno + 1 );
                m_pmutexs_[seqno] = new boost::mutex;
                //std::cout << alloc_lock id = "  << seqno << " lock addr = " << m_pmutexs_[seqno] << " this = " << this << std::endl;

                m_thread_mutex_.unlock();

                return seqno;
            }
        }