/* 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 */
}
Ejemplo n.º 2
0
char *
db_nextrec(DB *db, char *key)
{
    char    c, *ptr;

        /* We read lock the free list so that we don't read
           a record in the middle of its being deleted. */
    if (readw_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
        err_dump("readw_lock error");

    do {
            /* read next sequential index record */
        if (_db_readidx(db, 0) < 0) {
            ptr = NULL;        /* end of index file, EOF */
            goto doreturn;
        }
            /* check if key is all blank (empty record) */
        ptr = db->idxbuf;
        while ( (c = *ptr++) != 0  &&  c == ' ')
            ;    /* skip until null byte or nonblank */
    } while (c == 0);    /* loop until a nonblank key is found */

    if (key != NULL)
        strcpy(key, db->idxbuf);    /* return key */
    ptr = _db_readdat(db);    /* return pointer to data buffer */

    db->cnt_nextrec++;
doreturn:
    if (un_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
        err_dump("un_lock error");

    return(ptr);
}
/* Returning the sequential record...
Just gotta step ahead through the index file where we gotta ignore deleted records.
db_rewind() essential to be called before this function at initial stage itself */
char *db_nextrec(DB *db, char *key)
{
	char c, *ptr;
	/* Locking the free list where we don't actually read a record in the mid of deletion*/
	if(readw_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
		err_dump("error");
	do
	{
		/* read next sequential index record */
		if(_db_readidx(db, 0) < 0)
		{
			ptr = NULL; /* end of index file --- EOF */
			goto doreturn;
		}
		/* Checking if the key is still blank or empty record */
		ptr = db->idxbuf;
		while((c = *ptr++) != 0 && c = ' ');
		/* skip if it's not blank */
	}
	while(c == 0) /* loop untill a non-empty key is found*/
		if(key != NULL)
			strcpy(key, db->idxbuf); /* return key */
	ptr = _db_readdat(db); /* return pointer to data buffer */
	db->cnt_nextrec++;
doreturn:
	if(un_lock(db->idxfd, FREE_OFF, SEEK_SET, 1) < 0)
		err_dump("error");
}
Ejemplo n.º 4
0
void str_cli(register FILE *fp, register int sockfd) {
  int n;
  char sendline[MAXLINE];
  char recvline[MAXLINE + 1];

  while (fgets(sendline, MAXLINE, fp) != NULL) {
    n = strlen(sendline);

    if (writen(sockfd, sendline, n) != n) {
      printf("MAXLINE: %d, n: %d\n", MAXLINE, n);
      err_dump("str_cli : written error on socket");
    }

    n = readline(sockfd, recvline, MAXLINE);

    if (n < 0) {
      err_dump("str_cli : reading error");
    }
    recvline[n] = '\0';
    printf("Received string from Server: ");
    fputs(recvline, stdout);
  }

  if (ferror(fp)) {
    err_dump("str_cli : error reading file");
  }
}
/* 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");
}
Ejemplo n.º 6
0
int main(int argc, char *argv[]) {
  int sockfd;
  struct sockaddr_in serv_addr;
  pname = argv[0];

  //
  // Fill in the structure "serv_addr" with the address of
  // the server that we want to connect with
  //

  memset((char *) &serv_addr, 0, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = inet_addr(SERV_HOST_ADDR);
  serv_addr.sin_port = htons(SERV_TCP_PORT);

  //
  // Open a TCP socket (an Internet stream socket)
  //
  if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    err_dump("client : can't open stream socket");
  }

  //
  // Connect the server
  //
  if (connect(sockfd, (
      struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
    err_dump("client : can't connect to server");
  }

  str_cli(stdin, sockfd);
  close(sockfd);

  return EXIT_SUCCESS;
}
Ejemplo n.º 7
0
static int
myfunc(const char *pathname, const struct stat *statptr, int type)
{
    switch (type) {
    case FTW_F:
        switch (statptr->st_mode & S_IFMT) {
        case S_IFREG:    nreg++;        break;
        case S_IFBLK:    nblk++;        break;
        case S_IFCHR:    nchr++;        break;
        case S_IFIFO:    nfifo++;    break;
        case S_IFLNK:    nslink++;    break;
        case S_IFSOCK:    nsock++;    break;
        case S_IFDIR:    /* directories should have type = FTW_D */
            err_dump("for S_IFDIR for %s", pathname);
        }
        break;
    case FTW_D:
        ndir++;
        break;
    case FTW_DNR:
        err_ret("can't read directory %s", pathname);
        break;
    case FTW_NS:
        err_ret("stat error for %s", pathname);
        break;
    default:
        err_dump("unknown type %d for pathname %s", type, pathname);
    }
    return(0);
}
Ejemplo n.º 8
0
DB *
_db_alloc(int namelen)
{
    DB        *db;

            /* Use calloc, to init structure to zero */
    if ( (db = calloc(1, sizeof(DB))) == NULL)
        err_dump("calloc error for DB");

    db->idxfd = db->datfd = -1;                /* descriptors */

        /* Allocate room for the name.
           +5 for ".idx" or ".dat" plus null at end. */

    if ( (db->name = malloc(namelen + 5)) == NULL)
        err_dump("malloc error for name");

        /* Allocate an index buffer and a data buffer.
           +2 for newline and null at end. */

    if ( (db->idxbuf = malloc(IDXLEN_MAX + 2)) == NULL)
        err_dump("malloc error for index buffer");
    if ( (db->datbuf = malloc(DATLEN_MAX + 2)) == NULL)
        err_dump("malloc error for data buffer");

    return(db);
}
/* 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);
}
Ejemplo n.º 10
0
/*
 * receive a file descriptor from a server process. Also, any data
 * received is passed to (*userfunc)(STDERR_FILENO, buf, nbytes).
 * we have a 2-byte protocol for receiving the fd from send_fd().
 */
int recv_fd(int fd, ssize_t (*userfunc)(int, const void *, size_t))
{
	int		newfd, nr, status;
	char		*ptr;
	char		buf[MAXLINE];
	struct iovec	iov[1];
	struct msghdr	msg;

	status = -1;
	for (;;) {
		iov[0].iov_base	= buf;
		iov[0].iov_len	= sizeof(buf);
		msg.msg_iov	= iov;
		msg.msg_iovlen	= 1;
		msg.msg_name	= NULL;
		msg.msg_namelen	= 0;
		if (cmptr == NULL && (cmptr = malloc(CONTROLLEN)) == NULL)
			return -1;
		msg.msg_control	= cmptr;
		msg.msg_controllen = CONTROLLEN;
		if ((nr = recvmsg(fd, &msg, 0)) < 0) {
			err_ret("recvmsg error");
			return -1;
		} else if (nr == 0) {
			err_ret("connection closed by server");
			return -1;
		}

		/*
		 * see if this is the final data with null & status. null
		 * is next to last byte of buffer; status byte is last byte.
		 * zero status means there is a file descriptor to receive.
		 */
		for (ptr = buf; ptr < &buf[nr]; ) {
			if (*ptr++ == 0) {
				if (ptr != &buf[nr - 1])
					err_dump("message format error");
				/*
				 * prevent sign extension
				 */
				status = *ptr & 0xff;
				if (status == 0) {
					if (msg.msg_controllen < CONTROLLEN)
						err_dump("status = 0 but no fd");
					newfd = *(int *)CMSG_DATA(cmptr);
				} else {
					newfd = -status;
				}
				nr -= 2;
			}
		}
		if (nr > 0 && (*userfunc)(STDERR_FILENO, buf, nr) != nr)
			return -1;
		if (status >= 0)	/* final data has arrived */
			return newfd;	/* descriptor, or -status */
	}
}
/* Read a chain ptr field from anywhere in the index file:
--- the free list pointer, hash table chain ptr, or index record chain ptr */
off_t _db_readptr(DB *db, off_t offset)
{
	char asciiptr[PTR_SZ + 1];
	if(lseek(db->idxfd, offset, SEEK_SET) == -1)
		err_dump("error");
	if(read(db->idxfd, asciiptr, PTR_SZ) != PTR_SZ)
		err_dump("error");
	asciiptr[PTR_SZ] = 0; /* null terminate */
	return(atol(asciiptr));
}
/* Writing a chain ptr field somewhere in the index file:
	=== The free list
	=== The hash table
	=== index record
*/
void _db_writeptr(DB *db, off_t offset, off_t ptrval)
{
	char asciiptr[PTR_SZ + 1];
	if(ptrval < 0 || ptrval > PTR_MAX)
		err_quit("invalid ptr: %d", ptrval);
	sprintf(asciiptr, "%*d", PTR_SZ, ptrval);
	if(lseek(db->idxfd, offset, SEEK_SET) == -1)
		err_dump("error");
	if(write(db->idxfd, asciiptr, PTR_SZ) != PTR_SZ)
		err_dump("error");
}
/* Returning the pointer to the null terminated data buffer */
char *_db_readdat(DB *db)
{
	if(lseek(db->datfd, db->datoff, SEEK_SET) == -1)
		err_dump("error");
	if(read(db->datfd, db->datbuf, db->datlen) != db->datlen)
		err_dump("error");
	if(db->datbuf[db->datlen - 1] != '\n') /* clean checking */
		err_dump("missing newline");
	db->datbuf[db->datlen - 1] = 0; /* replace newline with NULL */
	return(db->datbuf); /* returns pointer to data record */
}
/* Reading next index record.
Starting at the specified offset in the index file.
Reading the index record into db->idxbuf and replacing the separators with null bytes.
If all were cool, then setting db->datoff and db->datlen to the offset & length of the corresponding data record in data file.
*/
off_t _db_readidx(DB *db, off_t offset)
{
	int i;
	char *ptr1, *ptr2;
	char asciiptr[PTR_SZ + 1], asciilen[IDXLEN_SZ + 1];
	struct iovec iov[2];
	/* Positioning index file and recording the offset.
	db_nextrec() calls with offset==0 which means reading from current offset.
	we still need to call lseek() to record the current offset. */
	if((db->idxoff = lseek(db->idxfd, offset, offset == 0 ? SEEK_CUR : SEEK_SET)) == -1)
		err_dump("error");
	/* Reading the ASCII chain ptr and ASCII length at the front of index record.
	This tells us the remaining size of the index record. */
	iov[0].iov_base = asciiptr;
	iov[0].iov_len = PTR_SZ;
	iov[1].iov_base = asciilen;
	iov[1].iov_len = IDXLEN_SZ;
	if((i = readv(db->idxfd, &iov[0], 2)) != PTR_SZ + IDXLEN_SZ)
	{
		if(i == 0 && offset == 0)
			return(-1); /* EOF for db_nextrec() */
	err_dump("error");
	}
asciiptr[PTR_SZ] = 0; /* null terminate */
db->ptrval = atol(asciiptr); /* offset of next key in chain */
							/* this is our return value, always >= 0 */
asciilen[IDXLEN_SZ] = 0; /* null terminate */
if((db->idxlen = atoi(asciilen)) < IDXLEN_MIN || db->idxlen > IDXLEN_MAX)
	err_dump("invalid length");
/* Now reading the actual index record. We'll be reading it into the buffer we have memory allocated after we opened a DB */
if((i = read(db->idxfd, db->idxbuf, db->idxlen)) != db->idxlen)
	err_dump("error");
if(db->idxbuf[db->idxlen-1] != '\n')
	err_dump("missing newline"); /* clean checking */
db->idxbuf[db->idxlen-1] = 0; /* replace newline with NULL */
/* Finding the separators in the index record */
if((ptr1 = strchr(db->idxbuf, SEP)) == NULL)
	err_dump("missing first separator");
*ptr1++ = 0;
if((ptr2 = strchr(ptr1, SEP)) == NULL)
	err_dump("missing seconf separator");
*ptr2++ = 0;
if(strchr(ptr2, SEP) != NULL)
	err_dump("too many separators");
/* Getting the initial offset and length of the data record */
if((db->datoff = atol(ptr1)) < 0)
	err_dump("initial offset < 0");
if((db->datlen = atol(ptr2)) <= 0 || db->datlen > DATLEN_MAX)
	err_dump("invalid length");
return(db->ptrval); /* return the offset of the next key in chain */
}
Ejemplo n.º 15
0
int main(int argc, char *argv[]) {
    int sockfd, newsockfd,  childpid;
    struct sockaddr_in cli_addr, serv_addr;
    socklen_t clilen;
    
    pname = argv[0];

    /* Open a TCP socker (an Internet stream socket). */
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        err_dump("Server: can't open stream socket\n");

    /* Bind our local address so that the client can send to us. */
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(SERV_TCP_PORT);

    if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
        err_dump("Server : can't bind local address\n");
    printf("\t[Info] binding...\n");

    listen(sockfd, 5);
    printf("\t[Info] listening...\n");

    for( ; ; ) {
        /* 
         * Wait for a connection from a client process.
         * This is an example of a concurrent server.
         */
        printf("\t[Info] wait for connection...\n");
        clilen = sizeof(cli_addr);
        newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
        char *paddr_str = inet_ntoa(cli_addr.sin_addr);
        printf("\t[Info] Receive connection from %s\n",paddr_str);
        if (newsockfd < 0)
            err_dump("server: accept error\n");

        if ( (childpid = fork()) < 0)
            err_dump("server: fork error\n");
        else if (childpid == 0) {
            close(sockfd);
            str_echo(newsockfd);
            exit(0);
        }

        close(newsockfd);
    }

    return 0;
}
Ejemplo n.º 16
0
/**
 * 1 lseek找到offset位置
 * 2读PTR_SZ 个字节到ptr
 * 3转换为证书返回
 */
off_t 
_db_readptr(DB * db,off_t offset)
{
	char asciiptr[PTR_SZ+1]; //7

	if(lseek(db->idxfd, offset, SEEK_SET) == -1)
		err_dump("lseek error ptr field");
	if(read(db->idxfd,asciiptr,PTR_SZ)!=PTRSZ)
		err_dump("read error of ptr field");

	asciiptr[PTR_SZ] =0;

	return (atol(asciiptr));

}
Ejemplo n.º 17
0
static void getfl(int fd){
	int val;
	if ((val = fcntl(fd, F_GETFL, 0)) < 0)
			err_sys("fcntl error for fd %d\n", fd);
		switch (val & O_ACCMODE) {
		case O_WRONLY:
			printf("write only");
			break;
		case O_RDONLY:
			printf("read only");
			break;
		case O_RDWR:
			printf("write read");
			break;
		default:
			err_dump("unknown access mode");
		}
		if (val & O_APPEND) {
			printf(",append");
		}
		if (val & O_NONBLOCK)
			printf(",noblock");

	#ifdef O_SYNC
		if (val & O_SYNC)
			printf(",sync");
	#endif
	#if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC)
		printf(",fsync");
	#endif
		putchar('\n');
}
int 
main(int argc, char *argv[])
{
	int val;

	if(argc != 2)
		err_quit("usage: filesign.out <descriptor#>");
	if((val = fcntl(atoi(argv[1]), F_GETFL, 0)) < 0)
		err_sys("fcntl error for fd %d", atoi(argv[1]));

	switch(val & O_ACCMODE){
	case O_RDONLY: printf("read only");break;
	case O_WRONLY: printf("write only");break;
	case O_RDWR: printf("read write");break;
	default: err_dump("unkown access mode");
	}

	if(val & O_APPEND)
		printf(", append");
	if(val & O_NONBLOCK)
		printf(", nonblocking");
	if(val & O_SYNC)
		printf(", synchronous writes");
	
#if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC) && (O_FSYNC != O_SYNC)
	if(val & O_FSYNC)
		printf(", synchronous writes");
#endif
	
	putchar('\n');
	exit(0);	
}
/* Free-ing up the database structure and all the memory allocated (malloc) buffers which are pointed.
And close the file descriptors if it's still open */
int _db_free(DB *db)
{
	if(db->idxfd >= 0 && close(db->idxfd) < 0)
		err_dump("error");
	if(db->datfd >= 0 && close(db->datfd) < 0)
		err_dump("error");
	db->idxfd = db->datfd = -1;
	if(db->idxbuf != NULL)
		free(db->idxbuf);
	if(db->datbuf != NULL)
		free(db->datbuf);
	if(db->name != NULL)
		free(db->name);
	free(db);
	return(0);
}
Ejemplo n.º 20
0
int
pthread_rwlock_unlock(pthread_rwlock_t *rw)
{
	int		result;

	if (rw->rw_magic != RW_MAGIC)
		return(EINVAL);

	if ( (result = pthread_mutex_lock(&rw->rw_mutex)) != 0)
		return(result);

	if (rw->rw_refcount > 0)
		rw->rw_refcount--;			/* releasing a reader */
	else if (rw->rw_refcount == -1)
		rw->rw_refcount = 0;		/* releasing a reader */
	else
		err_dump("rw_refcount = %d", rw->rw_refcount);


		/* 4give preference to waiting writers over waiting readers */
	if (rw->rw_nwaitwriters > 0)
		result = pthread_cond_signal(&rw->rw_condwriters);
	else if (rw->rw_nwaitreaders > 0)
		result = pthread_cond_broadcast(&rw->rw_condreaders);

	pthread_mutex_unlock(&rw->rw_mutex);
	return(result);
}
Ejemplo n.º 21
0
int main(int argc, char *argv[])
{
    int val;
    if(argc!=2)
        err_quit("usage: a.out <descriptor#>");

    if((val=fcntl(atoi(argv[1]),F_GETFL,0)) <  0)
        err_sys("fcntl error for fd %d", atoi(argv[1]));

    switch(val & O_ACCMODE) {
        case O_RDONLY:
            printf("read only");
            break;

        case O_WRONLY:
            printf("write only");
            break;

        case O_RDWR:
            printf("read & write");
            break;

        default:
            err_dump("unknown access mode");


    }

    if (val & O_APPEND)
        printf(",append");
    if( val & O_NONBLOCK)
        printf(",nonblocking");
    putchar('\n');
    exit(0);
}
Ejemplo n.º 22
0
int
main(int argc, char *argv[])
{
	int		accmode, val;

	if (argc != 2)
		err_quit("usage: a.out <descriptor#>");

	if ( (val = fcntl(atoi(argv[1]), F_GETFL, 0)) < 0)
		err_sys("fcntl error for fd %d", atoi(argv[1]));

	accmode = val & O_ACCMODE;
	if      (accmode == O_RDONLY)	printf("read only");
	else if (accmode == O_WRONLY)	printf("write only");
	else if (accmode == O_RDWR)		printf("read write");
	else err_dump("unknown access mode");

	if (val & O_APPEND)			printf(", append");
	if (val & O_NONBLOCK)		printf(", nonblocking");
#if	!defined(_POSIX_SOURCE) && defined(O_SYNC)
	if (val & O_SYNC)			printf(", synchronous writes");
#endif
	putchar('\n');
	exit(0);
}
Ejemplo n.º 23
0
static int loop(int n, const char *req, const char *rel)
{
	int reqfd, relfd;		 
	char buf[1];
	ssize_t nbytes;
	int i;
	

	for ( ; ; ) {
		if ((reqfd = open(req, O_RDONLY)) == -1) 
			return -1;
		
		for (i = 0; i < n; i++) {
			if ((nbytes = read(reqfd, buf, 1)) == -1)
				return -1;
			err_msg("i: %d read: %s pipe: %s\n", i, buf, req);
		}
		if (close(reqfd) == -1) 
			return -1;

		buf[0] = REL_CHAR;
		if ((relfd = open(rel, O_WRONLY)) == -1) 
			return -1;
		for (i = 0; i < n; i++) {
			if (write(relfd, buf, 1) != 1) 
				return -1;
		}
		if (close(relfd) == -1) 
			return -1;
	}      
	err_dump("loop: should not get here");
	return -1;
}
Ejemplo n.º 24
0
/**
 * 要做的操作 
 * 1 设置文件便宜
 * 2 读取数据
 * 3 将文件'\n' 替换成NULL
 * 4 返回dabuf
 */
char *
_db_readdat(DB *db)
{
	if(lseek(db->datfd,db->datoff,SEEK_SET)==-1)
		err_dump("lseek error");

	if(read(db->datfd,db->datbuf,db->datlen)!=db->datlen)
		err_dump("read error for dat");
	if(db->datbuf[db->datlen-1]!='\n')
		err_dump("missing newline");
	db->datbuf[db->datlen-1] =0;

	return db->datbuf;


}
Ejemplo n.º 25
0
void str_echo(int sockfd) {
    int n;
    char line[MAXLINE];

    for( ; ; ) {
        n = readline(sockfd, line, MAXLINE);
        if (n == 0)
            return;
        else if (n < 0)
            err_dump("str_echo: readline error:");
        
        strcat(line, " from server\n");
        if (writen(sockfd, line, n+14) != n+14)
            err_dump("str_echo: writen error");
    }
}
Ejemplo n.º 26
0
/*
 * open or create a database
 */
DBHANDLE db_open_error(const char* pathname, int oflags, ...)
{
	DB *db;
	int len, mode;
	size_t i;
	char asciiptr[PTR_SZ + 1], hash[(NHASH_DEF + 1) * PTR_SZ + 2];
	struct stat statbuf;

	len = strlen(pathname);
	if ((db = _db_alloc(len)) == NULL)
		err_dump("db_open: __db_alloc error for DB");

	//初始化db结构体
	db->nhash = NHASH_DEF;
	db->hashoff = HASH_OFF;
	strcpy(db->name, pathname);
	strcat(db->name, ".idx");

	//创建数据库文件
	if (oflags & O_CREAT)
	{
		va_list ap;
		va_start(ap, oflags);
		mode = va_arg(ap, int);
		va_end(ap);

		/*打开索引文件和数据文件*/
		db->idxfd = open(db->name, oflags, mode);
		strcpy(db->name + len, ".dat");
		db->datfd = open(db->name, oflags, mode);
	}
Ejemplo n.º 27
0
Archivo: dic.c Proyecto: lcion/nadcn
void smsg(char *msg){
int n;
	n = strlen(msg);
	if (writen(sockfdex, msg, n) != n)
			err_dump("<server> : strecho - eroare in writen");

}
Ejemplo n.º 28
0
void
sem_close(int id)
{
	register int	semval;

	/*
	 * The following semop() first gets a lock on the semaphore,
	 * then increments [1] - the process counter.
	 */

	if (semop(id, &op_close[0], 3) < 0)
		err_sys("can't semop");

	/*
	 * Now that we have a lock, read the value of the process
	 * counter to see if this is the last reference to the
	 * semaphore.
	 * There is a race condition here - see the comments in
	 * sem_create().
	 */

	if ((semval = semctl(id, 1, GETVAL, 0)) < 0)
		err_sys("can't GETVAL");

	if (semval > BIGCOUNT)
		err_dump("sem[1] > BIGCOUNT");
	else if (semval == BIGCOUNT)
		sem_rm(id);
	else
		if (semop(id, &op_unlock[0], 1) < 0)
			err_sys("can't unlock");	/* unlock */
}
Ejemplo n.º 29
0
static void sig_usr(int signo) {
	if(signo == SIGUSR1)
		printf("received SIGUSR1\n");
	else if(signo == SIGUSR2)
		printf("received SIGUSR2\n");
	else
		err_dump("received signal %d\n", signo);
}
Ejemplo n.º 30
0
int main(int argc, char const *argv[])
{
    int val;
    char *a;
    scanf("%s",&a);

    // if (argc != 2)
    // {
    //     err_quit("usage: a.out <descriptor#>");
    // }

    if ((val = fcntl(atoi(a),F_GETFL,0)) < 0)
    {
        err_sys("fcntl error for %d",atoi(a));
    }

    printf("%d\n", (val & O_ACCMODE));

    switch (val & O_ACCMODE){
        case O_RDONLY:
        printf("read only\n");
        break;

        case O_WRONLY:
        printf("write only\n");
        break;

        case O_RDWR:
        printf("read write\n");
        break;

        default:
        err_dump("unknow access mode");
    }

    if (val & O_APPEND)
    {
        printf(", append\n");
    }
    if (val & O_NONBLOCK)
    {
        printf(", nonblocking\n");
    }
    if (val & O_SYNC)
    {
        printf(",synchronous writes\n");
    }

    #if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC) && (O_FSYNC != O_SYNC)
        if (val & O_FSYNC)
        {
            printf(", synchronous writes\n");
        }
    #endif
        putchar('\n');
        exit(0);
}