utils.c

来自「openGFS , a kind of file system.」· C语言 代码 · 共 151 行

C
151
字号
/* * *    Copyright 2000-2001 Sistina Software, Inc. * *    This is free software released under the GNU General Public License. *    There is no warranty for this software.  See the file COPYING for *    details. * *    See the file AUTHORS for a list of contributors. *  */#include <unistd.h>#include <stdlib.h>#include <sys/socket.h>#include <netinet/in.h>#include <stdio.h>#include <string.h>#include "utils.h"unsigned int match(char *name, serv_list_t *ptr){	for (; ptr; ptr = ptr->next) {		if (strcmp(name, ptr->name) == 0)			return ptr->port;	}	return 0;}int get_pid(char *name, serv_list_t *ptr){	for (; ptr; ptr = ptr->next) {		if (strcmp(name, ptr->name) == 0)			return ptr->pid;	}	return -1;}serv_list_t *remove_serv(char *name, serv_list_t *head){	serv_list_t *current, *last;	if (!head)		return NULL;	last = head;	current = head->next;	if (strcmp(head->name, name) == 0) {		free(head);		return current;	}	while (current) {		if (strcmp(current->name, name) == 0) {			last->next = current->next;			free(current);			return head;		}		last = current;		current = current->next;	}	return head;}serv_list_t *add(serv_list_t item, serv_list_t *head){	serv_list_t *tmp = malloc(sizeof(serv_list_t)), *ptr;	strcpy(tmp->name, item.name);	strcpy(tmp->path, item.path);	tmp->port = item.port;	tmp->pid = item.pid;	tmp->next = NULL;	if (!head)		return tmp;	for (ptr = head; ptr->next; ptr = ptr->next)		;	ptr->next = tmp;	return head;}serv_list_t *clear(serv_list_t *ptr){	serv_list_t *tmp;	while (ptr) {		tmp = ptr;		ptr = ptr->next;		free(tmp);	}	return NULL;}int close_socket(int val){	if (val > 0)		close(val);	return 0;}int open_socket(int tcp, int port){	struct sockaddr_in sin;	int s;	if ((s = socket(AF_INET, tcp ? SOCK_STREAM : SOCK_DGRAM , 0) < 0)) {		perror("gportd: error creating socket");		return s;	}	sin.sin_family = AF_INET;	sin.sin_addr.s_addr = INADDR_ANY;	sin.sin_port = htons(port);	if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {		perror("gportd: error binding the socket");		goto fail;	}	if (!tcp)		return s;	if (listen(s, 5) < 0) {		perror("gportd: error listening on the socket");		goto fail;	}	return s;fail:	close(s);	return -1;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?