您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ syslog函数代码示例

51自学网 2021-06-03 08:38:26
  C++
这篇教程C++ syslog函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中syslog函数的典型用法代码示例。如果您正苦于以下问题:C++ syslog函数的具体用法?C++ syslog怎么用?C++ syslog使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了syslog函数的29个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: strncpy

//.........这里部分代码省略.........	// Start read thread 	if ( NULL == 			( m_hTreadReceive = CreateThread(	NULL,										0,										(LPTHREAD_START_ROUTINE) workThreadReceive,										this,										0,										&threadId ) ) ) { 		// Failure		close();		return  false;	}		// Release the mutex	UNLOCK_MUTEX( m_apoxMutex );	UNLOCK_MUTEX( m_receiveMutex );	UNLOCK_MUTEX( m_transmitMutex );	UNLOCK_MUTEX( m_responseMutex );#else // LINUX	pthread_attr_t thread_attr;	pthread_attr_init( &thread_attr );			// Create the log write thread.	if ( pthread_create( 	&m_threadId,								&thread_attr,								workThreadTransmit,								this ) ) {										syslog( LOG_CRIT, "canallogger: Unable to create apoxdrv write thread.");		rv = false;		fclose( m_flog );	}	// Create the log write thread.	if ( pthread_create( 	&m_threadId,								&thread_attr,								workThreadReceive,								this ) ) {										syslog( LOG_CRIT, "canallogger: Unable to create apoxdrv receive thread.");		rv = false;		fclose( m_flog );	}		    // We are open	m_bOpen = true;	// Release the mutex	pthread_mutex_unlock( &m_apoxMutex );#endif		// Switch to main mode if in boot mode	if ( RUNMODE_BOOT == getAdapterRunMode() ) {		setAdapterRunMode( RUNMODE_MAIN );	}	// Set baudrate	setBaudrate( nSpeed );
开发者ID:davidlcamlin,项目名称:vscp_software,代码行数:66,


示例2: masterconn_download_data

void masterconn_download_data(masterconn *eptr,const uint8_t *data,uint32_t length) {	uint64_t offset;	uint32_t leng;	uint32_t crc;	ssize_t ret;	if (eptr->metafd<0) {		syslog(LOG_NOTICE,"MATOAN_DOWNLOAD_DATA - file not opened");		eptr->mode = KILL;		return;	}	if (length<16) {		syslog(LOG_NOTICE,"MATOAN_DOWNLOAD_DATA - wrong size (%"PRIu32"/16+data)",length);		eptr->mode = KILL;		return;	}	passert(data);	offset = get64bit(&data);	leng = get32bit(&data);	crc = get32bit(&data);	if (leng+16!=length) {		syslog(LOG_NOTICE,"MATOAN_DOWNLOAD_DATA - wrong size (%"PRIu32"/16+%"PRIu32")",length,leng);		eptr->mode = KILL;		return;	}	if (offset!=eptr->dloffset) {		syslog(LOG_NOTICE,"MATOAN_DOWNLOAD_DATA - unexpected file offset (%"PRIu64"/%"PRIu64")",offset,eptr->dloffset);		eptr->mode = KILL;		return;	}	if (offset+leng>eptr->filesize) {		syslog(LOG_NOTICE,"MATOAN_DOWNLOAD_DATA - unexpected file size (%"PRIu64"/%"PRIu64")",offset+leng,eptr->filesize);		eptr->mode = KILL;		return;	}#ifdef HAVE_PWRITE	ret = pwrite(eptr->metafd,data,leng,offset);#else /* HAVE_PWRITE */	lseek(eptr->metafd,offset,SEEK_SET);	ret = write(eptr->metafd,data,leng);#endif /* HAVE_PWRITE */	if (ret!=(ssize_t)leng) {		mfs_errlog_silent(LOG_NOTICE,"error writing metafile");		if (eptr->downloadretrycnt>=5) {			masterconn_download_end(eptr);		} else {			eptr->downloadretrycnt++;			masterconn_download_next(eptr);		}		return;	}	if (crc!=mycrc32(0,data,leng)) {		syslog(LOG_NOTICE,"metafile data crc error");		if (eptr->downloadretrycnt>=5) {			masterconn_download_end(eptr);		} else {			eptr->downloadretrycnt++;			masterconn_download_next(eptr);		}		return;	}	if (fsync(eptr->metafd)<0) {		mfs_errlog_silent(LOG_NOTICE,"error syncing metafile");		if (eptr->downloadretrycnt>=5) {			masterconn_download_end(eptr);		} else {			eptr->downloadretrycnt++;			masterconn_download_next(eptr);		}		return;	}	eptr->dloffset+=leng;	eptr->downloadretrycnt=0;	masterconn_download_next(eptr);}
开发者ID:davies,项目名称:moosefs,代码行数:74,


示例3: disk_activity

/*  * disk_activity() returns back the total number of read and writes done  * by the devices listed in the io watch table since the last call to  * disk_activity.  The number of reads and writes are determined by  * opening and reading each of the valid files listed in the io watch  * table.The number of reads and writes are stored in the io watch table so  * that the next call to this routine can compare the current number of read  * and writes to those stored in the io watch table. The difference for  * each device is summed in the activity variable.  The routine lazy  * evaluates the existance of the devices in the table.  * * For the storcenter, we are only concerned with internal drives.  * * The wt_path element must point at a diskstat file in the sysfs filesystem.   * File format can be found at: /usr/src/linux/Documentation/iostats.txt * For this routine: *	nr, nw - number read and writes *	nmr, nmw - number of merged reads and writes *	nsr, nsw - number of the sectors read and written *	tr, tw - time spent reading and writing *	nio - raw number of ios  * 	tio, wtio - time spent and weighted time spent doing io */intdisk_activity(){	int	activity = 0;	char	mesg[256];	int	rc, nr, nmr, nsr, tr, nw, nmw, nsw, tw, nio, tio, wtio;	FILE	*f;	struct stat		st;	struct watch_table	*w;	for (w = iowt; w->wt_path; w++) {		/*		 * If status ids set to check, do the lazy existence 		 * evaluation. If stat fails set to invalid. Don't 		 * worry about perms here. 		 */		if ((w->wt_status == WT_CHECK) && 		    (stat(w->wt_path, &st) < 0)) {			sprintf(mesg, "%s not available", w->wt_path);			syslog(LOG_INFO, mesg);			w->wt_status = WT_INVALID;		}		/*		 * Short circuit the loop if invalid.		 */		if (w->wt_status == WT_INVALID) 			continue;		/*		 * If it can't be opened rdonly, set to invalid		 */		if ((f = fopen(w->wt_path, "r")) < 0) {			sprintf(mesg, "Unable to open %s, no longer watching",				w->wt_path);			syslog(LOG_INFO, mesg);			w->wt_status = WT_INVALID;			continue;		}		rc = fscanf(f, "%d %d %d %d %d %d %d %d %d %d %d", 		       &nr, &nmr, &nsr, &tr,		       &nw, &nmw, &nsw, &tw,		       &nio, &tio, &wtio);		fclose(f);		if (rc != 11) {			sprintf(mesg, "Unable to read %s", w->wt_path);			syslog(LOG_INFO, mesg);			continue;		}		/*		 * If we haven't seen any activity on this device before		 * then just save the values and go on. This, although		 * not strictly necessary, prevents the initial call to 		 * disk_activity returning back the base set io activity.		 * Remember it takes two calls to get a true difference.		 */		if ((w->wt_reads == 0) && (w->wt_writes == 0)) {			w->wt_reads  = nr;			w->wt_writes = nw;			continue;		}		activity += (nr - w->wt_reads);		activity += (nw - w->wt_writes);		w->wt_reads  = nr;		w->wt_writes = nw;		/*		   printf("%s: %d %d %d %d %d %d %d %d %d %d %d/n",		       w->wt_path,		       nr, nmr, nsr, tr,//.........这里部分代码省略.........
开发者ID:4doe,项目名称:openembedded,代码行数:101,


示例4: main

int main(int argc, char *argv[]){	int error __unused, i, r, s;	FILE *pidf;	int ch = 0;	while ((ch = getopt(argc, argv, "d")) != -1) {		switch(ch) {		case 'd':			debugopt = 1;			break;		default:			usage();			/* NOT REACHED */		}	}	argc -= optind;	argv += optind;	TAILQ_INIT(&pdev_array_list);	TAILQ_INIT(&udev_monitor_list);	r = ignore_signal(SIGPIPE);	if (r != 0)		err(1, "could not ignore_signal SIGPIPE");	r = pthread_mutex_init(&(monitor_lock), NULL);	if (r != 0)		err(1, "could not allocate a pthread_mutex");	if ((udevfd = open(UDEV_DEVICE_PATH, O_RDWR | O_NONBLOCK)) == -1)		err(1, "%s", UDEV_DEVICE_PATH);	unblock_descriptor(udevfd);	s = init_local_server(LISTEN_SOCKET_FILE, SOCK_STREAM, 0);	if (s < 0)		err(1, "init_local_server");	pidf = fopen("/var/run/udevd.pid", "w");#if 0	if (pidf == NULL)		err(1, "pidfile");#endif	set_signal(SIGTERM, killed);	set_signal(SIGHUP, hangup);	if (debugopt == 0)		if (daemon(0, 0) == -1)			err(1, "daemon");	if (pidf != NULL) {		fprintf(pidf, "%ld/n", (long)getpid());		fclose(pidf);	}	syslog(LOG_ERR, "udevd started");	pdev_array_entry_insert(udev_getdevs(udevfd));	memset(fds, 0 , sizeof(fds));	fds[UDEV_DEVICE_FD_IDX].fd = udevfd;	fds[UDEV_DEVICE_FD_IDX].events = POLLIN;	fds[UDEV_SOCKET_FD_IDX].fd = s;	fds[UDEV_SOCKET_FD_IDX].events = POLLIN | POLLPRI;	for (;;) {		r = poll(fds, NFDS, -1);		if (r < 0) {			if (hangup_ongoing == 0) {				if (errno == EINTR) {					usleep(5000);					continue;				} else {					err(1, "polling...");				}			} else {				usleep(20000); /* 20 ms */				continue;			}		}		for (i = 0; (i < NFDS) && (r > 0); i++) {			if (fds[i].revents == 0)				continue;			--r;			switch (i) {			case UDEV_DEVICE_FD_IDX:				udev_read_event(udevfd);				break;			case UDEV_SOCKET_FD_IDX:				handle_new_connection(s);				break;			default:				break;			}		}	}//.........这里部分代码省略.........
开发者ID:alexandermerritt,项目名称:dragonfly,代码行数:101,


示例5: syslog

    int StateVersion::OnVersionInfo (const IPacket &packet)    {        uint8_t locale = packet.Read<uint8_t>();        std::string ID = packet.Read();        uint32_t version = packet.Read<uint32_t>();        if (!packet.EndOfStream())            return MSG_ERROR_SIZE;        boost::shared_ptr<Server> server = m_service->getServer();        if (!server)            return MSG_ERROR;        if (locale != server->Locale() || ID != server->ClientID())        {            syslog(LOG_INFO,"Trying to log with a different locale");            return MSG_ERROR_ARG;        }        if (version == server->ClientVersion())        {            m_connection->setState(srv::STATE_LOGIN);            OPacket pkt;            srv_pkt::WriteVersionE(&pkt);            m_connection->send(&pkt);            pkt.Clear();            srv_pkt::WriteVersionF(&pkt);   ///PERFORM UPDATE PACKET!!            m_connection->send(&pkt);        }        else if (version < server->ClientVersion())        {            OPacket pkt(0x600D);            pkt.Write<uint8_t>(1);            pkt.Write<uint16_t>(1);            pkt.Write<uint16_t>(0xA100);            m_connection->send(&pkt);            pkt.Clear();            pkt.WriteOpcode(0x600D);            pkt.Write<uint8_t>(0);            pkt.Write<uint8_t>(2);            pkt.Write<uint8_t>(5);            m_connection->send(&pkt);    //		///REDIRECT TO UPDATE SERVER!!!    //		m_connection->Stop();        }        else        {            /// TOO NEW            OPacket pkt(0x600D);            pkt.Write<uint8_t>(1);            pkt.Write<uint16_t>(1);            pkt.Write<uint16_t>(0xA100);            m_connection->send(&pkt);            pkt.Clear();            pkt.WriteOpcode(0x600D);            pkt.Write<uint8_t>(0);            pkt.Write<uint8_t>(2);            pkt.Write<uint8_t>(1);            m_connection->send(&pkt);        }        return MSG_SUCCESS;    }
开发者ID:Favorek,项目名称:ZelosOnline,代码行数:74,


示例6: getifstats

intgetifstats(const char * ifname, struct ifdata * data){	FILE *f;	char line[512];	char * p;	int i;	int r = -1;#ifdef ENABLE_GETIFSTATS_CACHING	static time_t cache_timestamp = 0;	static struct ifdata cache_data;	time_t current_time;#endif	data->baudrate = 4200000;	data->opackets = 0;	data->ipackets = 0;	data->obytes = 0;	data->ibytes = 0;#ifdef ENABLE_GETIFSTATS_CACHING	current_time = time(NULL);	if(current_time == ((time_t)-1)) {		syslog(LOG_ERR, "getifstats() : time() error : %m");	} else {		if(current_time < cache_timestamp + GETIFSTATS_CACHING_DURATION) {			memcpy(data, &cache_data, sizeof(struct ifdata));			return 0;		}	}#endif	f = fopen("/proc/net/dev", "r");	if(!f) {		syslog(LOG_ERR, "getifstats() : cannot open /proc/net/dev : %m");		return -1;	}	/* discard the two header lines */	fgets(line, sizeof(line), f);	fgets(line, sizeof(line), f);	while(fgets(line, sizeof(line), f)) {		p = line;		while(*p==' ') p++;		i = 0;		while(ifname[i] == *p) {			p++; i++;		}		/* TODO : how to handle aliases ? */		if(ifname[i] || *p != ':')			continue;		p++;		while(*p==' ') p++;		data->ibytes = strtoul(p, &p, 0);		while(*p==' ') p++;		data->ipackets = strtoul(p, &p, 0);		/* skip 6 columns */		for(i=6; i>0 && *p!='/0'; i--) {			while(*p==' ') p++;			while(*p!=' ' && *p) p++;		}		while(*p==' ') p++;		data->obytes = strtoul(p, &p, 0);		while(*p==' ') p++;		data->opackets = strtoul(p, &p, 0);		r = 0;		break;	}	fclose(f);#ifdef ENABLE_GETIFSTATS_CACHING	if(r==0 && current_time!=((time_t)-1)) {		cache_timestamp = current_time;		memcpy(&cache_data, data, sizeof(struct ifdata));	}#endif	return r;}
开发者ID:WiseMan787,项目名称:ralink_sdk,代码行数:73,


示例7: logg

//.........这里部分代码省略.........        }#endif    }    if (logg_fp)    {        char flush = !logg_noflush;        /* Need to avoid logging time for verbose messages when logverbose               is not set or we get a bunch of timestamps in the log without               newlines... */        if (logg_time && ((*buff != '*') || logg_verbose))        {            char timestr[32];            time(&currtime);            cli_ctime(&currtime, timestr, sizeof(timestr));            /* cut trailing /n */            timestr[strlen(timestr) - 1] = '/0';            fprintf(logg_fp, "%s -> ", timestr);        }        if (*buff == '!')        {            fprintf(logg_fp, "ERROR: %s", buff + 1);            flush = 1;        }        else if (*buff == '^')        {            if (!logg_nowarn)                fprintf(logg_fp, "WARNING: %s", buff + 1);            flush = 1;        }        else if (*buff == '*' || *buff == '$')        {            fprintf(logg_fp, "%s", buff + 1);        }        else if (*buff == '#' || *buff == '~')        {            fprintf(logg_fp, "%s", buff + 1);        }        else            fprintf(logg_fp, "%s", buff);        if (flush)            fflush(logg_fp);    }    if (logg_foreground)    {        if (buff[0] != '#')        {            if (logg_time)            {                char timestr[32];                time(&currtime);                cli_ctime(&currtime, timestr, sizeof(timestr));                /* cut trailing /n */                timestr[strlen(timestr) - 1] = '/0';                mprintf("%s -> %s", timestr, buff);            }            else            {                mprintf("%s", buff);            }        }    }#if defined(USE_SYSLOG) && !defined(C_AIX)    if (logg_syslog)    {        cli_chomp(buff);        if (buff[0] == '!')        {            syslog(LOG_ERR, "%s", buff + 1);        }        else if (buff[0] == '^')        {            if (!logg_nowarn)                syslog(LOG_WARNING, "%s", buff + 1);        }        else if (buff[0] == '*' || buff[0] == '$')        {            syslog(LOG_DEBUG, "%s", buff + 1);        }        else if (buff[0] == '#' || buff[0] == '~')        {            syslog(LOG_INFO, "%s", buff + 1);        }        else            syslog(LOG_INFO, "%s", buff);    }#endif#ifdef CL_THREAD_SAFE    pthread_mutex_unlock(&logg_mutex);#endif    if (len > sizeof(buffer))        free(abuffer);    return 0;}
开发者ID:vrtadmin,项目名称:clamav-devel,代码行数:101,


示例8: relayGotSessionPacket

/***********************************************************************%FUNCTION: relayGotSessionPacket*%ARGUMENTS:* iface -- interface on which packet is waiting*%RETURNS:* Nothing*%DESCRIPTION:* Receives and processes a session packet.***********************************************************************/voidrelayGotSessionPacket(PPPoEInterface const *iface){    PPPoEPacket packet;    int size;    SessionHash *sh;    PPPoESession *ses;    if (receivePacket(iface->sessionSock, &packet, &size) < 0) {	return;    }    /* Ignore unknown code/version */    if (packet.ver != 1 || packet.type != 1) {	return;    }    /* Must be a session packet */    if (packet.code != CODE_SESS) {	syslog(LOG_ERR, "Session packet with code %d", (int) packet.code);	return;    }    /* Ignore session packets whose destination address isn't ours */    if (memcmp(packet.ethHdr.h_dest, iface->mac, ETH_ALEN)) {	return;    }    /* Validate length */    if (ntohs(packet.length) + HDR_SIZE > size) {	syslog(LOG_ERR, "Bogus PPPoE length field (%u)",	       (unsigned int) ntohs(packet.length));	return;    }    /* Drop Ethernet frame padding */    if (size > ntohs(packet.length) + HDR_SIZE) {	size = ntohs(packet.length) + HDR_SIZE;    }    /* We're in business!  Find the hash */    sh = findSession(packet.ethHdr.h_source, packet.session);    if (!sh) {	/* Don't log this.  Someone could be running the client and the	   relay on the same box. */	return;    }    /* Relay it */    ses = sh->ses;    ses->epoch = Epoch;    sh = sh->peer;    packet.session = sh->sesNum;    memcpy(packet.ethHdr.h_source, sh->interface->mac, ETH_ALEN);    memcpy(packet.ethHdr.h_dest, sh->peerMac, ETH_ALEN);#if 0    fprintf(stderr, "Relaying %02x:%02x:%02x:%02x:%02x:%02x(%s:%d) to %02x:%02x:%02x:%02x:%02x:%02x(%s:%d)/n",	    sh->peer->peerMac[0], sh->peer->peerMac[1], sh->peer->peerMac[2],	    sh->peer->peerMac[3], sh->peer->peerMac[4], sh->peer->peerMac[5],	    sh->peer->interface->name, ntohs(sh->peer->sesNum),	    sh->peerMac[0], sh->peerMac[1], sh->peerMac[2],	    sh->peerMac[3], sh->peerMac[4], sh->peerMac[5],	    sh->interface->name, ntohs(sh->sesNum));#endif    sendPacket(NULL, sh->interface->sessionSock, &packet, size);}
开发者ID:berte,项目名称:mediaplayer,代码行数:75,


示例9: relayHandlePADI

/***********************************************************************%FUNCTION: relayHandlePADI*%ARGUMENTS:* iface -- interface on which packet was received* packet -- the PADI packet*%RETURNS:* Nothing*%DESCRIPTION:* Receives and processes a PADI packet.***********************************************************************/voidrelayHandlePADI(PPPoEInterface const *iface,		PPPoEPacket *packet,		int size){    PPPoETag tag;    unsigned char *loc;    int i, r;    int ifIndex;    /* Can a client legally be behind this interface? */    if (!iface->clientOK) {	syslog(LOG_ERR,	       "PADI packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not permitted",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    /* Source address must be unicast */    if (NOT_UNICAST(packet->ethHdr.h_source)) {	syslog(LOG_ERR,	       "PADI packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not from a unicast address",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    /* Destination address must be broadcast */    if (NOT_BROADCAST(packet->ethHdr.h_dest)) {	syslog(LOG_ERR,	       "PADI packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not to a broadcast address",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    /* Get array index of interface */    ifIndex = iface - Interfaces;    loc = findTag(packet, TAG_RELAY_SESSION_ID, &tag);    if (!loc) {	tag.type = htons(TAG_RELAY_SESSION_ID);	tag.length = htons(MY_RELAY_TAG_LEN);	memcpy(tag.payload, &ifIndex, sizeof(ifIndex));	memcpy(tag.payload+sizeof(ifIndex), packet->ethHdr.h_source, ETH_ALEN);	/* Add a relay tag if there's room */	r = addTag(packet, &tag);	if (r < 0) return;	size += r;    } else {	/* We do not re-use relay-id tags.  Drop the frame.  The RFC says the	   relay agent SHOULD return a Generic-Error tag, but this does not	   make sense for PADI packets. */	return;    }    /* Broadcast the PADI on all AC-capable interfaces except the interface       on which it came */    for (i=0; i < NumInterfaces; i++) {	if (iface == &Interfaces[i]) continue;	if (!Interfaces[i].acOK) continue;	memcpy(packet->ethHdr.h_source, Interfaces[i].mac, ETH_ALEN);	sendPacket(NULL, Interfaces[i].discoverySock, packet, size);    }}
开发者ID:berte,项目名称:mediaplayer,代码行数:93,


示例10: relayHandlePADS

/***********************************************************************%FUNCTION: relayHandlePADS*%ARGUMENTS:* iface -- interface on which packet was received* packet -- the PADS packet*%RETURNS:* Nothing*%DESCRIPTION:* Receives and processes a PADS packet.***********************************************************************/voidrelayHandlePADS(PPPoEInterface const *iface,		PPPoEPacket *packet,		int size){    PPPoETag tag;    unsigned char *loc;    int ifIndex;    int acIndex;    PPPoESession *ses = NULL;    SessionHash *sh;    /* Can a server legally be behind this interface? */    if (!iface->acOK) {	syslog(LOG_ERR,	       "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not permitted",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    acIndex = iface - Interfaces;    /* Source address must be unicast */    if (NOT_UNICAST(packet->ethHdr.h_source)) {	syslog(LOG_ERR,	       "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not from a unicast address",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    /* Destination address must be interface's MAC address */    if (memcmp(packet->ethHdr.h_dest, iface->mac, ETH_ALEN)) {	return;    }    /* Find relay tag */    loc = findTag(packet, TAG_RELAY_SESSION_ID, &tag);    if (!loc) {	syslog(LOG_ERR,	       "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s does not have Relay-Session-Id tag",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    /* If it's the wrong length, ignore it */    if (ntohs(tag.length) != MY_RELAY_TAG_LEN) {	syslog(LOG_ERR,	       "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s does not have correct length Relay-Session-Id tag",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    /* Extract interface index */    memcpy(&ifIndex, tag.payload, sizeof(ifIndex));    if (ifIndex < 0 || ifIndex >= NumInterfaces ||	!Interfaces[ifIndex].clientOK ||	iface == &Interfaces[ifIndex]) {	syslog(LOG_ERR,	       "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s has invalid interface in Relay-Session-Id tag",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],//.........这里部分代码省略.........
开发者ID:berte,项目名称:mediaplayer,代码行数:101,


示例11: createSession

/***********************************************************************%FUNCTION: createSession*%ARGUMENTS:* ac -- Ethernet interface on access-concentrator side* cli -- Ethernet interface on client side* acMac -- Access concentrator's MAC address* cliMac -- Client's MAC address* acSess -- Access concentrator's session ID.*%RETURNS:* PPPoESession structure; NULL if one could not be allocated*%DESCRIPTION:* Initializes relay hash table and session tables.***********************************************************************/PPPoESession *createSession(PPPoEInterface const *ac,	      PPPoEInterface const *cli,	      unsigned char const *acMac,	      unsigned char const *cliMac,	      UINT16_t acSes){    PPPoESession *sess;    SessionHash *acHash, *cliHash;    if (NumSessions >= MaxSessions) {	printErr("Maximum number of sessions reached -- cannot create new session");	return NULL;    }    /* Grab a free session */    sess = FreeSessions;    FreeSessions = sess->next;    NumSessions++;    /* Link it to the active list */    sess->next = ActiveSessions;    if (sess->next) {	sess->next->prev = sess;    }    ActiveSessions = sess;    sess->prev = NULL;    sess->epoch = Epoch;    /* Get two hash entries */    acHash = FreeHashes;    cliHash = acHash->next;    FreeHashes = cliHash->next;    acHash->peer = cliHash;    cliHash->peer = acHash;    sess->acHash = acHash;    sess->clientHash = cliHash;    acHash->interface = ac;    cliHash->interface = cli;    memcpy(acHash->peerMac, acMac, ETH_ALEN);    acHash->sesNum = acSes;    acHash->ses = sess;    memcpy(cliHash->peerMac, cliMac, ETH_ALEN);    cliHash->sesNum = sess->sesNum;    cliHash->ses = sess;    addHash(acHash);    addHash(cliHash);    /* Log */    syslog(LOG_INFO,	   "Opened session: server=%02x:%02x:%02x:%02x:%02x:%02x(%s:%d), client=%02x:%02x:%02x:%02x:%02x:%02x(%s:%d)",	   acHash->peerMac[0], acHash->peerMac[1],	   acHash->peerMac[2], acHash->peerMac[3],	   acHash->peerMac[4], acHash->peerMac[5],	   acHash->interface->name,	   ntohs(acHash->sesNum),	   cliHash->peerMac[0], cliHash->peerMac[1],	   cliHash->peerMac[2], cliHash->peerMac[3],	   cliHash->peerMac[4], cliHash->peerMac[5],	   cliHash->interface->name,	   ntohs(cliHash->sesNum));    return sess;}
开发者ID:berte,项目名称:mediaplayer,代码行数:84,


示例12: relayHandlePADR

/***********************************************************************%FUNCTION: relayHandlePADR*%ARGUMENTS:* iface -- interface on which packet was received* packet -- the PADR packet*%RETURNS:* Nothing*%DESCRIPTION:* Receives and processes a PADR packet.***********************************************************************/voidrelayHandlePADR(PPPoEInterface const *iface,		PPPoEPacket *packet,		int size){    PPPoETag tag;    unsigned char *loc;    int ifIndex;    int cliIndex;    /* Can a client legally be behind this interface? */    if (!iface->clientOK) {	syslog(LOG_ERR,	       "PADR packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not permitted",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    cliIndex = iface - Interfaces;    /* Source address must be unicast */    if (NOT_UNICAST(packet->ethHdr.h_source)) {	syslog(LOG_ERR,	       "PADR packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not from a unicast address",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    /* Destination address must be interface's MAC address */    if (memcmp(packet->ethHdr.h_dest, iface->mac, ETH_ALEN)) {	return;    }    /* Find relay tag */    loc = findTag(packet, TAG_RELAY_SESSION_ID, &tag);    if (!loc) {	syslog(LOG_ERR,	       "PADR packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s does not have Relay-Session-Id tag",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    /* If it's the wrong length, ignore it */    if (ntohs(tag.length) != MY_RELAY_TAG_LEN) {	syslog(LOG_ERR,	       "PADR packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s does not have correct length Relay-Session-Id tag",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;    }    /* Extract interface index */    memcpy(&ifIndex, tag.payload, sizeof(ifIndex));    if (ifIndex < 0 || ifIndex >= NumInterfaces ||	!Interfaces[ifIndex].acOK ||	iface == &Interfaces[ifIndex]) {	syslog(LOG_ERR,	       "PADR packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s has invalid interface in Relay-Session-Id tag",	       packet->ethHdr.h_source[0],	       packet->ethHdr.h_source[1],	       packet->ethHdr.h_source[2],	       packet->ethHdr.h_source[3],	       packet->ethHdr.h_source[4],	       packet->ethHdr.h_source[5],	       iface->name);	return;//.........这里部分代码省略.........
开发者ID:berte,项目名称:mediaplayer,代码行数:101,


示例13: while

void DirWatcher::Run(){	// Load torrents already in place	this->LoadInitial();		if(this->inotifyfd>=0){		char buf[1024];		// Add watches on all current directories		this->AddWatches();				// Monitor /home for new and removed users		this->AddHomeWatch();		// TODO: implement timeout and a way to terminate thread		ssize_t l;		struct inotify_event *item;			int itemsize;		while(doRun){			if((l=read(this->inotifyfd,buf,sizeof(buf)))<0){				if(errno != EINTR){					syslog(LOG_NOTICE,"Read event failed: %m");				}			}else{				item=(inotify_event *)buf;						while(l>=(ssize_t)(sizeof(struct inotify_event)+item->len)){					itemsize=(sizeof(struct inotify_event)+item->len);					if(item->len ){						if(this->iwatches[item->wd]=="/home/"){							syslog(LOG_DEBUG,"dirwatcher: user %s trigged",item->name);							// This is an action on the home watch							string pth="/home/"+string(item->name)+"/"+									FtdConfig::Instance().GetStringOrDefault("torrent","torrentdir","torrents")+									"/";							if(item->mask & IN_CREATE){								// New user								// Hack to let system add skeleton dir								sleep(1);								this->AddWatch(pth);							}else if(item->mask & IN_DELETE){								// User deleted, do nothing. Watch removed when torrent dir deleted								//this->DelWatch(pth);							}else{								syslog(LOG_NOTICE, "Unknown event on home dir: %s",pth.c_str());							}						}else{							// TODO: add watch on delete as well.							// This is an ordinary action on a torrent dir							if(item->mask && (IN_CREATE|IN_MOVED_TO)){								// We have a new file, only add if its not our "own"								if(strncmp(item->name,".ftdtr",6)==0){									syslog(LOG_DEBUG,"Not readding download");								}else{									string dlpath=this->iwatches[item->wd]+string(item->name);									//AFP hack									sleep(1);									this->AddDownload(dlpath);								}							}else{								syslog(LOG_NOTICE,"dirwatcher: Unknown event on %s",item->name);							}						}					}					l-=itemsize;					item=(struct inotify_event*)(((unsigned long)item)+itemsize);				}			}					}	}				syslog(LOG_NOTICE,"Dirwatcher terminating");}
开发者ID:Excito,项目名称:filetransferdaemon,代码行数:70,


示例14: pam_restauth_check

/* RESTAuth request dispatcher */static int pam_restauth_check(        const char *base_url,        const char *service_user,        const char *service_password,        const char *group,        int validate_certificate,        const char *user,        const char *password) {    /* allocate structures */    CURL *session = curl_easy_init();    char *escaped_user = url_escape(user);    char *escaped_password = url_escape(password);    char *url = malloc(strlen(base_url)+strlen("/users/")+strlen(user)*3+1+1);    char *post_data = malloc(strlen("password=")+strlen(password)*3+1);    int ret = -1;    if (!session || !escaped_user || !escaped_password || !url || !post_data)        goto cleanup;    /* create URL: <base url>/users/<user>/ */    sprintf(url, "%s%susers/%s/", base_url,            *(base_url+strlen(base_url)-1) == '/' ? "":"/",            escaped_user);    /* create POST data: password=<password> */    sprintf(post_data, "password=%s", escaped_password);    /* set up CURL request */    pam_restauth_curl_session_init(session, url,                                   service_user, service_password,                                   validate_certificate, post_data);    /* perform request */    long curl_http_code = 0;    int curl_status = curl_easy_perform(session);    curl_status += curl_easy_getinfo(session, CURLINFO_RESPONSE_CODE,                                     &curl_http_code);    if (curl_status == CURLE_OK && curl_http_code >= 200 && curl_http_code < 300) {        /* success. perform group check if a group is specified */        if (group) {            /* create group URL */            char *escaped_group = url_escape(group);            char *group_url = malloc(strlen(base_url)+strlen("/groups/")+strlen(escaped_group)+strlen("/users/")+strlen(escaped_user)+1);            sprintf(group_url, "%s%sgroups/%s/users/%s/", base_url,                    *(base_url+strlen(base_url)-1) == '/' ? "":"/",                    escaped_group, escaped_user);            /* set up CURL request again and perform call */            pam_restauth_curl_session_init(session, group_url,                                           service_user, service_password,                                           validate_certificate, NULL);            curl_status = curl_easy_perform(session);            curl_status += curl_easy_getinfo(session, CURLINFO_RESPONSE_CODE,                                             &curl_http_code);            if (curl_status == CURLE_OK && curl_http_code >= 200 && curl_http_code < 300) {                ret = 0; /* success */            }            else {                ret = -1; /* failure */                syslog(LOG_AUTHPRIV|LOG_NOTICE, __FILE__": user `%s' failed RESTAuth check for group `%s'", escaped_user, escaped_group);            }            if (escaped_group) free(escaped_group);            if (group_url) free(group_url);        }        else {            ret = 0; /* success */        }    }    else {        ret = -1; /* failure */    }cleanup:    if (session) curl_easy_cleanup(session);    if (escaped_user) free(escaped_user);    if (escaped_password) free(escaped_password);    if (url) free(url);    if (post_data) free(post_data);    return ret;}
开发者ID:RestAuth,项目名称:pam,代码行数:87,


示例15: getPlatformAndDeviceInfo

void getPlatformAndDeviceInfo(cl_platform_id* platformIds, cl_uint maxPlatforms, cl_uint myPlatform, cl_device_type devType){  /* See how many platforms are available.*/  cl_uint numPlatforms;  cl_int status = clGetPlatformIDs(maxPlatforms, platformIds, &numPlatforms);  statusCheck(status, "clGetPlatformIds");  printf("%d platform(s) detected./n", numPlatforms);  /* Get the names of the platforms and display to user. */  char platNames[maxPlatforms][100];  uint plat = 0;  for(plat = 0; plat < numPlatforms; plat++){    size_t nameBufferLength;    status = clGetPlatformInfo(platformIds[plat], CL_PLATFORM_NAME, sizeof(platNames[plat]), platNames[plat], &nameBufferLength);    statusCheck(status, "clGetPlatformInfo");    printf("/tPlatform %d: %s/n", plat, platNames[plat]);  }    /* see how many devices our chosen platform platform ...*/  const cl_uint maxDevices = 4;  cl_device_id deviceIds[maxDevices];  cl_uint numDevices;  clGetDeviceIDs(platformIds[myPlatform], devType, maxDevices, deviceIds, &numDevices);  statusCheck(status, "clGetDeviceIDs");    /* Give up if we can't find any devices on chosen platform */  if (numDevices==0) {    syslog(LOG_ERR, "Error! 0 devices found on platform %s!/n", platNames[myPlatform]);    syslog(LOG_ERR, "This normally means I can't talk to the X server for some reason./n");    syslog(LOG_ERR, "Exiting program./n");    fprintf(stderr, "Error! 0 devices found on platform %s!/n", platNames[myPlatform]);    fprintf(stderr, "This normally means I can't talk to the X server for some reason./n");    fprintf(stderr, "Exiting program./n");    exit(1);  }  /* Prints useful information about the GPU architecture to the screen.*/  size_t maxWorkGroupSize;  char devNames[maxDevices][100];  uint dev=0;  for(dev = 0; dev < numDevices; dev++){    size_t length;    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_NAME, sizeof(devNames[dev]), devNames, &length);    statusCheck(status, "clGetDeviceInfo");         cl_bool available;    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_AVAILABLE, sizeof(available), &available, &length);    statusCheck(status, "clGetDeviceInfo");         cl_uint maxComputeUnits;    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(maxComputeUnits), &maxComputeUnits, &length);    statusCheck(status, "clGetDeviceInfo");         cl_uint maxWorkItemDimension;    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(maxWorkItemDimension), &maxWorkItemDimension, &length);    statusCheck(status, "clGetDeviceInfo");    size_t maxWorkItemSizes[maxWorkItemDimension];    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(maxWorkItemSizes), &maxWorkItemSizes, &length);    statusCheck(status, "clGetDeviceInfo");    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(maxWorkGroupSize), &maxWorkGroupSize, &length);    statusCheck(status, "clGetDeviceInfo");    cl_ulong maxMemAllocSize = 0;    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(maxMemAllocSize), &maxMemAllocSize, &length);    statusCheck(status, "clGetDeviceInfo");          cl_ulong deviceLocalMemSize = 0;    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_LOCAL_MEM_SIZE, sizeof(deviceLocalMemSize), &deviceLocalMemSize, &length);    statusCheck(status, "clGetDeviceInfo");    printf("/t/tDevice: %d/n", dev);    printf("/t/tName: %s/n", devNames[dev]);    printf("/t/tAvailable: ");    if(available){printf("Yes");}    else{printf("No");}    printf("/n/t/tNumber of Compute Units: %d/n", maxComputeUnits);    printf("/t/tNumber of Work Item dimensions: %d/n", maxWorkItemDimension);    printf("/t/tMax Work Items for each dimension: ");    uint dim=0; for(dim = 0; dim < maxWorkItemDimension; dim++){ printf("%ld ", maxWorkItemSizes[dim]);}    printf("/n/t/tMax Work Group size: %ld/n", maxWorkGroupSize);    printf("/t/tGlobal memory size (bytes): %ld/n", maxMemAllocSize);    printf("/t/tLocal memory size (bytes): %ld/n", deviceLocalMemSize);  }}
开发者ID:sylarcp,项目名称:anitaFlightSoft,代码行数:86,


示例16: log_error_write

//.........这里部分代码省略.........		}		buffer_copy_string_buffer(srv->errorlog_buf, srv->ts_debug_str);		buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(": ("));		break;	case ERRORLOG_SYSLOG:		/* syslog is generating its own timestamps */		buffer_copy_string_len(srv->errorlog_buf, CONST_STR_LEN("("));		break;	}	buffer_append_string(srv->errorlog_buf, filename);	buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN("."));	buffer_append_long(srv->errorlog_buf, line);	buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(") "));	for(va_start(ap, fmt); *fmt; fmt++) {		int d;		char *s;		buffer *b;		off_t o;		switch(*fmt) {		case 's':           /* string */			s = va_arg(ap, char *);			buffer_append_string(srv->errorlog_buf, s);			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(" "));			break;		case 'b':           /* buffer */			b = va_arg(ap, buffer *);			buffer_append_string_buffer(srv->errorlog_buf, b);			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(" "));			break;		case 'd':           /* int */			d = va_arg(ap, int);			buffer_append_long(srv->errorlog_buf, d);			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(" "));			break;		case 'o':           /* off_t */			o = va_arg(ap, off_t);			buffer_append_off_t(srv->errorlog_buf, o);			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(" "));			break;		case 'x':           /* int (hex) */			d = va_arg(ap, int);			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN("0x"));			buffer_append_long_hex(srv->errorlog_buf, d);			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(" "));			break;		case 'S':           /* string */			s = va_arg(ap, char *);			buffer_append_string(srv->errorlog_buf, s);			break;		case 'B':           /* buffer */			b = va_arg(ap, buffer *);			buffer_append_string_buffer(srv->errorlog_buf, b);			break;		case 'D':           /* int */			d = va_arg(ap, int);			buffer_append_long(srv->errorlog_buf, d);			break;		case 'O':           /* off_t */			o = va_arg(ap, off_t);			buffer_append_off_t(srv->errorlog_buf, o);			break;		case 'X':           /* int (hex) */			d = va_arg(ap, int);			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN("0x"));			buffer_append_long_hex(srv->errorlog_buf, d);			break;		case '(':		case ')':		case '<':		case '>':		case ',':		case ' ':			buffer_append_string_len(srv->errorlog_buf, fmt, 1);			break;		}	}	va_end(ap);	switch(srv->errorlog_mode) {	case ERRORLOG_PIPE:	case ERRORLOG_FILE:		buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN("/n"));		write(srv->errorlog_fd, srv->errorlog_buf->ptr, srv->errorlog_buf->used - 1);		break;	case ERRORLOG_STDERR:		buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN("/n"));		write(STDERR_FILENO, srv->errorlog_buf->ptr, srv->errorlog_buf->used - 1);		break;	case ERRORLOG_SYSLOG:		syslog(LOG_ERR, "%s", srv->errorlog_buf->ptr);		break;	}	return 0;}
开发者ID:presidentbeef,项目名称:sqwee,代码行数:101,


示例17: nis_lerror

voidnis_lerror (const nis_error status, const char *label){  syslog (LOG_ERR, "%s: %s", label, nis_sperrno (status));}
开发者ID:riscv,项目名称:riscv-glibc,代码行数:5,


示例18: main

intmain(int argc, char *const *argv){	struct sockaddr_in bindaddr;	socklen_t addrlen;	const char *isDA;	const char *proxyReg;	int connfd;	int lfd;	const int on = 1;	detachfromtty();	openlog("slpd", LOG_PID, LOG_DAEMON);	do_args(argc, argv);	/* If slpd has been configured to run as a DA, start it and exit */	isDA = SLPGetProperty("net.slp.isDA");	proxyReg = SLPGetProperty("net.slp.serializedRegURL");	if ((isDA && (strcasecmp(isDA, "true") == 0)) || proxyReg) {		run_slpd();		return (1);	}	if ((lfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {		syslog(LOG_ERR, "socket failed: %s", strerror(errno));		cleanup_and_exit(1);	}	(void) setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on));	(void) memset((void *)&bindaddr, 0, sizeof (bindaddr));	bindaddr.sin_family = AF_INET;	bindaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);	bindaddr.sin_port = htons(427);	if (bind(lfd, (const struct sockaddr *)&bindaddr, sizeof (bindaddr))	    < 0) {		syslog(LOG_ERR, "bind failed: %s", strerror(errno));		cleanup_and_exit(1);	}	if (listen(lfd, 1) < 0) {		syslog(LOG_ERR, "listen failed: %s", strerror(errno));		cleanup_and_exit(1);	}	addrlen = sizeof (bindaddr);	if ((connfd = accept(lfd, (struct sockaddr *)&bindaddr, &addrlen))	    < 0) {		syslog(LOG_ERR, "accept failed: %s", strerror(errno));		cleanup_and_exit(1);	}	(void) close(lfd);	(void) dup2(connfd, 0);	(void) close(connfd);	(void) dup2(0, 1);	(void) dup2(0, 2);	run_slpd();	return (1);}
开发者ID:AlainODea,项目名称:illumos-gate,代码行数:66,


示例19: main

int main ( int argc, char * argv[] ){	int have_committed = 1; // prevent double commits, 'clean' state to begin with        int c;	program_name = argv[0];	program_name = "ipbatch CLI";	// this is really important for locating shared libs	program_version = IPTABLES_VERSION;        c = xtables_init_all(&iptables_globals, NFPROTO_IPV4);        if (c < 0) {                fprintf(stderr, "%s/%s Failed to initialize xtables/n",                                program_name,                                program_version);                exit(1);        }	openlog( "SmoothIPSubsys", LOG_NDELAY | LOG_CONS, LOG_DAEMON );	/*        lib_dir = getenv("IPTABLES_LIB_DIR");*//*	if (!lib_dir)*//*		lib_dir = IPT_LIB_DIR;*/	/* read lines from STDIN */	char buffer[ BUFFER_SIZE ];	int error = 0;	// syslog( LOG_ERR, "Checking input" );	// there are two special commands end is the same as eof and commit	// does an early commit rather than the changes only being committed at the end	while ( fgets( buffer, BUFFER_SIZE - 2, stdin ) != NULL ){		/* terminate the line at the carriage return */		if ( strlen( buffer ) > BUFFER_SIZE ){			// silently ignore long lines			continue;		}		buffer[ strlen( buffer ) - 1 ] = '/0';		//syslog( LOG_ERR, "Received command %s", buffer );		if ( strcmp( buffer, "end" ) == 0 ){			break;		}		if ( strcmp( buffer, "commit" ) == 0 ){			/* commit changes */			error = iptc_commit(handle);			iptc_free(handle);			handle = NULL;			have_committed = 1;		} else {			/* excute the command */			if(!have_committed) {				if(table_changed(buffer)) {   					//syslog( LOG_ERR, "Table change for %s", buffer );					error = iptc_commit(handle);					iptc_free(handle);					handle = NULL;					have_committed = 1;				}			}			if(*buffer)			    error = execute( buffer );			have_committed = 0;		}		if ( !error ){			/* if an error has occured then we're */			/* in trouble and might as well just  */			/* leave                              */			syslog( LOG_ERR, "error: %s", iptc_strerror(errno));			return !error;		}	}	//syslog( LOG_ERR, "Finished" );	/* commit the changes, that is flush */	/* the iptables buffer               */	if(!have_committed) {		error = iptc_commit(handle);		iptc_free(handle);		handle = NULL;		syslog( LOG_ERR, "Unable to commit IPTables rules /"%s/"", iptc_strerror( errno ) );	}	return !error;}
开发者ID:afghanistanyn,项目名称:Smoothwall-Express-E3-Phaeton-Development-Project,代码行数:94,


示例20: udev_read_event

voidudev_read_event(int fd){	struct pdev_array_entry	*pae;	prop_dictionary_t	dict, evdict, devdict;	prop_number_t		pn;	prop_string_t		ps;	prop_object_t		po;	prop_array_t		pa;	char	*xml;	int	n, idx, evtype;	size_t	sz;	sz = 4096 * 1024;	xml = malloc(sz); /* 4 MB */again:	if ((n = read(fd, xml, sz)) <= 0) {		if (errno == ENOMEM) {			sz <<= 2;			if ((xml = realloc(xml, sz)) == NULL) {				syslog(LOG_ERR, "could not realloc xml memory");				return;			}			goto again;		}		free(xml);		return;	}	dict = prop_dictionary_internalize(xml);	free(xml);	if (dict == NULL) {		syslog(LOG_ERR, "internalization of xml failed");		return;	}	pn = prop_dictionary_get(dict, "evtype");	if (pn == NULL) {		syslog(LOG_ERR, "read_event: no key evtype");		goto out;	}	evtype = prop_number_integer_value(pn);	evdict = prop_dictionary_get(dict, "evdict");	if (evdict == NULL) {		syslog(LOG_ERR, "read_event: no key evdict");		goto out;	}	switch (evtype) {	case UDEV_EVENT_ATTACH:		monitor_queue_event(dict);		pae = pdev_array_entry_get_last();		pa = prop_array_copy(pae->pdev_array);		pdev_array_entry_unref(pae);		if (pa == NULL)			goto out;		prop_array_add(pa, evdict);		pdev_array_entry_insert(pa);		break;	case UDEV_EVENT_DETACH:		monitor_queue_event(dict);		if ((devdict = find_dev_dict(-1, evdict, &idx)) == NULL)			goto out;		pae = pdev_array_entry_get_last();		pa = prop_array_copy(pae->pdev_array);		pdev_array_entry_unref(pae);		if (pa == NULL)			goto out;		prop_array_remove(pa, idx);		pdev_array_entry_insert(pa);		break;	case UDEV_EV_KEY_UPDATE:		if ((devdict = find_dev_dict(-1, evdict, NULL)) == NULL)			goto out;		if ((ps = prop_dictionary_get(evdict, "key")) == NULL)			goto out;		if ((po = prop_dictionary_get(evdict, "value")) == NULL)			goto out;		/* prop_object_retain(po); */ /* not necessary afaik */		prop_dictionary_set(devdict, prop_string_cstring_nocopy(ps), po);		break;	case UDEV_EV_KEY_REMOVE:		if ((devdict = find_dev_dict(-1, evdict, NULL)) == NULL)			goto out;		if ((ps = prop_dictionary_get(evdict, "key")) == NULL)			goto out;		prop_dictionary_remove(devdict, prop_string_cstring_nocopy(ps));		break;	default:		syslog(LOG_ERR, "read_event: unknown evtype %d", evtype);	}out://.........这里部分代码省略.........
开发者ID:alexandermerritt,项目名称:dragonfly,代码行数:101,


示例21: cupsdCheckLogFile

//.........这里部分代码省略.........      if (!strncmp(filename, CUPS_LOGDIR, strlen(CUPS_LOGDIR)))      {       /*        * Try updating the permissions of the containing log directory, using	* the log file permissions as a basis...	*/        mode_t log_dir_perm = (mode_t)(0300 | LogFilePerm);					/* LogFilePerm + owner write/search */	if (log_dir_perm & 0040)	  log_dir_perm |= 0010;		/* Add group search */	if (log_dir_perm & 0004)	  log_dir_perm |= 0001;		/* Add other search */        cupsdCheckPermissions(CUPS_LOGDIR, NULL, log_dir_perm, RunUser, Group, 1, -1);        *lf = cupsFileOpen(filename, "a");      }      if (*lf == NULL)      {#ifdef HAVE_ASL_H	asl_object_t	m;		/* Log message */	m = asl_new(ASL_TYPE_MSG);	asl_set(m, ASL_KEY_FACILITY, "org.cups.cupsd");	asl_log(NULL, m, ASL_LEVEL_ERR, "Unable to open log file /"%s/" - %s", filename, strerror(errno));	asl_release(m);#elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)        sd_journal_print(LOG_ERR, "Unable to open log file /"%s/" - %s", filename, strerror(errno));#else	syslog(LOG_ERR, "Unable to open log file /"%s/" - %s", filename, strerror(errno));#endif /* HAVE_ASL_H */        if (FatalErrors & CUPSD_FATAL_LOG)	  cupsdEndProcess(getpid(), 0);	return (0);      }    }    if (strncmp(filename, "/dev/", 5))    {     /*      * Change ownership and permissions of non-device logs...      */      fchown(cupsFileNumber(*lf), RunUser, Group);      fchmod(cupsFileNumber(*lf), LogFilePerm);    }  } /*  * Do we need to rotate the log?  */  if (strncmp(logname, "/dev/", 5) && cupsFileTell(*lf) > MaxLogSize &&      MaxLogSize > 0)  {   /*    * Rotate log file...    */    cupsFileClose(*lf);
开发者ID:jianglei12138,项目名称:cups,代码行数:67,


示例22: logprintfl

//.........这里部分代码省略.........                size = snprintf(s, left, "%5s", l);                break;            }        case 'p':{                // process ID                char p[11];                snprintf(p, sizeof(p), "%010d", getpid());  // 10 chars is enough for max 32-bit unsigned integer                size = print_field_truncated(&prefix_spec, s, left, p);                break;            }        case 't':{                // thread ID                char t[21];                snprintf(t, sizeof(t), "%020d", (pid_t) syscall(SYS_gettid));   // 20 chars is enough for max 64-bit unsigned integer                size = print_field_truncated(&prefix_spec, s, left, t);                break;            }        case 'm':            // method            size = print_field_truncated(&prefix_spec, s, left, func);            break;        case 'F':{                // file-and-line                char file_and_line[64];                snprintf(file_and_line, sizeof(file_and_line), "%s:%d", file, line);                size = print_field_truncated(&prefix_spec, s, left, file_and_line);                break;            }        case 's':{                // max RSS of the process                struct rusage u;                bzero(&u, sizeof(struct rusage));                getrusage(RUSAGE_SELF, &u);                // unfortunately, many fields in 'struct rusage' aren't supported on Linux (notably: ru_ixrss, ru_idrss, ru_isrss)                char size_str[64];                snprintf(size_str, sizeof(size_str), "%05ld", u.ru_maxrss / 1024);                size = print_field_truncated(&prefix_spec, s, left, size_str);                break;            }        case '?':            // not supported currently            s[0] = '?';            s[1] = '/0';            size = 1;            break;        default:            s[0] = *prefix_spec;            s[1] = '/0';            size = 1;            break;        }        if (size < 0) {            // something went wrong in the snprintf()s above            logprintf("error in prefix construction in logprintfl()/n");            return -1;        }        offset += size;    }    // add a space between the prefix and the message proper    if ((offset > 0) && ((sizeof(buf) - offset - 1) > 0)) {        buf[offset++] = ' ';        buf[offset] = '/0';    }    // append the log message passed via va_list    va_start(ap, format);    {        rc = vsnprintf(buf + offset, sizeof(buf) - offset - 1, format, ap);    }    va_end(ap);    if (rc < 0)        return (rc);    if (syslog_facility != -1) {        // log to syslog, at the appropriate level: euca DEBUG, TRACE, and EXTREME use syslog's DEBUG        int l = LOG_DEBUG;        if (level == EUCA_LOG_ERROR)            l = LOG_ERR;        else if (level == EUCA_LOG_WARN)            l = LOG_WARNING;        else if (level == EUCA_LOG_INFO)            l = LOG_INFO;        if (custom_spec)            syslog(l, buf);        else            syslog(l, buf + offset);    }    return (log_line(buf));}
开发者ID:DeanSheehan,项目名称:eucalyptus,代码行数:101,


示例23: main

//.........这里部分代码省略.........		if (inet_pton(AF_INET, bind_address, &sin.sin_addr) != 1)			err(1, "inet_pton");	} else		sin.sin_addr.s_addr = htonl(INADDR_ANY);	sin.sin_family = AF_INET;	sin.sin_port = htons(port);	if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1)		err(1, "bind");	memset(&lin, 0, sizeof sin);	lin.sin_len = sizeof(sin);	lin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);	lin.sin_family = AF_INET;	lin.sin_port = htons(cfg_port);	if (bind(conflisten, (struct sockaddr *)&lin, sizeof lin) == -1)		err(1, "bind local");	if (syncsend || syncrecv) {		syncfd = sync_init(sync_iface, sync_baddr, sync_port);		if (syncfd == -1)			err(1, "sync init");	}	pw = getpwnam("_spamd");	if (!pw)		pw = getpwnam("nobody");#ifdef __FreeBSD__	/* open the pid file just before daemon */	fpid = fopen(pid_file, "w");	if (fpid == NULL) {		syslog(LOG_ERR, "exiting (couldn't create pid file %s)", 			pid_file);		err(1, "couldn't create pid file /"%s/"", pid_file);	}#endif		if (debug == 0) {		if (daemon(1, 1) == -1)			err(1, "daemon");	}	if (greylist) {#ifdef __FreeBSD__		if(use_pf){#endif						pfdev = open("/dev/pf", O_RDWR);			if (pfdev == -1) {				syslog_r(LOG_ERR, &sdata, "open /dev/pf: %m");				exit(1);			}#ifdef __FreeBSD__		} 	#endif		maxblack = (maxblack >= maxcon) ? maxcon - 100 : maxblack;		if (maxblack < 0)			maxblack = 0;		/* open pipe to talk to greylister */		if (pipe(greypipe) == -1) {			syslog(LOG_ERR, "pipe (%m)");			exit(1);		}
开发者ID:BackupTheBerlios,项目名称:freebsdspamd-svn,代码行数:67,


示例24: masterconn_metachanges_log

void masterconn_metachanges_log(masterconn *eptr,const uint8_t *data,uint32_t length) {	char logname1[100],logname2[100];	uint32_t i;	uint64_t version;	if (length==1 && data[0]==0x55) {		if (eptr->logfd!=NULL) {			fclose(eptr->logfd);			eptr->logfd=NULL;		}		if (BackLogsNumber>0) {			for (i=BackLogsNumber ; i>0 ; i--) {				snprintf(logname1,100,"changelog_ml.%"PRIu32".mfs",i);				snprintf(logname2,100,"changelog_ml.%"PRIu32".mfs",i-1);				rename(logname2,logname1);			}		} else {			unlink("changelog_ml.0.mfs");		}		return;	}	if (length<10) {		syslog(LOG_NOTICE,"MATOAN_METACHANGES_LOG - wrong size (%"PRIu32"/9+data)",length);		eptr->mode = KILL;		return;	}	if (data[0]!=0xFF) {		syslog(LOG_NOTICE,"MATOAN_METACHANGES_LOG - wrong packet");		eptr->mode = KILL;		return;	}	if (data[length-1]!='/0') {		syslog(LOG_NOTICE,"MATOAN_METACHANGES_LOG - invalid string");		eptr->mode = KILL;		return;	}	data++;	version = get64bit(&data);	if (lastlogversion>0 && version!=lastlogversion+1) {		syslog(LOG_WARNING, "some changes lost: [%"PRIu64"-%"PRIu64"], download metadata again",lastlogversion,version-1);		if (eptr->logfd!=NULL) {			fclose(eptr->logfd);			eptr->logfd=NULL;		}		for (i=0 ; i<=BackLogsNumber ; i++) {			snprintf(logname1,100,"changelog_ml.%"PRIu32".mfs",i);			unlink(logname1);		}		lastlogversion = 0;		eptr->mode = KILL;		return;	}	if (eptr->logfd==NULL) {		eptr->logfd = fopen("changelog_ml.0.mfs","a");	}	if (eptr->logfd) {		fprintf(eptr->logfd,"%"PRIu64": %s/n",version,data);		lastlogversion = version;	} else {		syslog(LOG_NOTICE,"lost MFS change %"PRIu64": %s",version,data);	}}
开发者ID:davies,项目名称:moosefs,代码行数:65,


示例25: log__vprintf

int log__vprintf(int priority, const char *fmt, va_list va){	char *s;	char *st;	int len;#ifdef WIN32	char *sp;#endif	const char *topic;	int syslog_priority;	time_t now = time(NULL);	static time_t last_flush = 0;	if((log_priorities & priority) && log_destinations != MQTT3_LOG_NONE){		switch(priority){			case MOSQ_LOG_SUBSCRIBE:				topic = "$SYS/broker/log/M/subscribe";#ifndef WIN32				syslog_priority = LOG_NOTICE;#else				syslog_priority = EVENTLOG_INFORMATION_TYPE;#endif				break;			case MOSQ_LOG_UNSUBSCRIBE:				topic = "$SYS/broker/log/M/unsubscribe";#ifndef WIN32				syslog_priority = LOG_NOTICE;#else				syslog_priority = EVENTLOG_INFORMATION_TYPE;#endif				break;			case MOSQ_LOG_DEBUG:				topic = "$SYS/broker/log/D";#ifndef WIN32				syslog_priority = LOG_DEBUG;#else				syslog_priority = EVENTLOG_INFORMATION_TYPE;#endif				break;			case MOSQ_LOG_ERR:				topic = "$SYS/broker/log/E";#ifndef WIN32				syslog_priority = LOG_ERR;#else				syslog_priority = EVENTLOG_ERROR_TYPE;#endif				break;			case MOSQ_LOG_WARNING:				topic = "$SYS/broker/log/W";#ifndef WIN32				syslog_priority = LOG_WARNING;#else				syslog_priority = EVENTLOG_WARNING_TYPE;#endif				break;			case MOSQ_LOG_NOTICE:				topic = "$SYS/broker/log/N";#ifndef WIN32				syslog_priority = LOG_NOTICE;#else				syslog_priority = EVENTLOG_INFORMATION_TYPE;#endif				break;			case MOSQ_LOG_INFO:				topic = "$SYS/broker/log/I";#ifndef WIN32				syslog_priority = LOG_INFO;#else				syslog_priority = EVENTLOG_INFORMATION_TYPE;#endif				break;#ifdef WITH_WEBSOCKETS			case MOSQ_LOG_WEBSOCKETS:				topic = "$SYS/broker/log/WS";#ifndef WIN32				syslog_priority = LOG_DEBUG;#else				syslog_priority = EVENTLOG_INFORMATION_TYPE;#endif				break;#endif			default:				topic = "$SYS/broker/log/E";#ifndef WIN32				syslog_priority = LOG_ERR;#else				syslog_priority = EVENTLOG_ERROR_TYPE;#endif		}		len = strlen(fmt) + 500;		s = mosquitto__malloc(len*sizeof(char));		if(!s) return MOSQ_ERR_NOMEM;		vsnprintf(s, len, fmt, va);		s[len-1] = '/0'; /* Ensure string is null terminated. */		if(log_destinations & MQTT3_LOG_STDOUT){			if(int_db.config && int_db.config->log_timestamp){				fprintf(stdout, "%d: %s/n", (int)now, s);			}else{//.........这里部分代码省略.........
开发者ID:PierreF,项目名称:mosquitto,代码行数:101,


示例26: masterconn_read

void masterconn_read(masterconn *eptr,double now) {	int32_t i;	uint32_t type,leng;	const uint8_t *ptr;	uint32_t rbleng,rbpos;	uint8_t err,hup;	static uint8_t *readbuff = NULL;	static uint32_t readbuffsize = 0;	if (eptr == NULL) {		if (readbuff != NULL) {			free(readbuff);		}		readbuff = NULL;		readbuffsize = 0;		return;	}	if (readbuffsize==0) {		readbuffsize = 65536;		readbuff = malloc(readbuffsize);		passert(readbuff);	}	rbleng = 0;	err = 0;	hup = 0;	for (;;) {		i = read(eptr->sock,readbuff+rbleng,readbuffsize-rbleng);		if (i==0) {			hup = 1;			break;		} else if (i<0) {			if (ERRNO_ERROR) {				err = 1;			}			break;		} else {			stats_bytesin+=i;			rbleng += i;			if (rbleng==readbuffsize) {				readbuffsize*=2;				readbuff = realloc(readbuff,readbuffsize);				passert(readbuff);			} else {				break;			}		}	}	if (rbleng>0) {		eptr->lastread = now;	}	rbpos = 0;	while (rbpos<rbleng) {		if ((rbleng-rbpos)>=eptr->input_bytesleft) {			memcpy(eptr->input_startptr,readbuff+rbpos,eptr->input_bytesleft);			i = eptr->input_bytesleft;		} else {			memcpy(eptr->input_startptr,readbuff+rbpos,rbleng-rbpos);			i = rbleng-rbpos;		}		rbpos += i;		eptr->input_startptr+=i;		eptr->input_bytesleft-=i;		if (eptr->input_bytesleft>0) {			break;		}		if (eptr->input_packet == NULL) {			ptr = eptr->input_hdr;			type = get32bit(&ptr);			leng = get32bit(&ptr);			if (leng>MaxPacketSize) {				syslog(LOG_WARNING,"Master packet too long (%"PRIu32"/%u)",leng,MaxPacketSize);				eptr->input_end = 1;				return;			}			eptr->input_packet = malloc(offsetof(in_packetstruct,data)+leng);			passert(eptr->input_packet);			eptr->input_packet->next = NULL;			eptr->input_packet->type = type;			eptr->input_packet->leng = leng;			eptr->input_startptr = eptr->input_packet->data;			eptr->input_bytesleft = leng;		}		if (eptr->input_bytesleft>0) {			continue;		}		if (eptr->input_packet != NULL) {			*(eptr->inputtail) = eptr->input_packet;			eptr->inputtail = &(eptr->input_packet->next);			eptr->input_packet = NULL;//.........这里部分代码省略.........
开发者ID:davies,项目名称:moosefs,代码行数:101,


示例27: pam_sm_authenticate

PAM_EXTERN intpam_sm_authenticate(pam_handle_t *pamh, int flags,                    int argc, const char *argv[]){    const char *user;    char *password;    int pam_err, retry;    const char *url = NULL;    const char *service_user = NULL;    const char *service_password = NULL;    const char *group = NULL;    const char *domain = NULL;    int validate_certificate = 0;    char *stripped_user = NULL;    /* parse all parameters */    {        int i = 0;        while (i < argc) {            const char *val;            if ((val = string_prefix_match(argv[i], "url=")) != NULL)                url = val;            else if ((val = string_prefix_match(argv[i], "service_user=")) != NULL)                service_user = val;            else if ((val = string_prefix_match(argv[i], "service_password=")) != NULL)                service_password = val;            else if ((val = string_prefix_match(argv[i], "group=")) != NULL)                group = val;            else if ((val = string_prefix_match(argv[i], "validate_certificate=")) != NULL)                validate_certificate = !!strcmp(val, "no"); /* no = 0, everything else = 1 */            else if ((val = string_prefix_match(argv[i], "domain=")) != NULL)                domain = val;            i++;        }    }    /* complain about missing arguments, return error */    if (!url || !(*url))        syslog(LOG_AUTHPRIV|LOG_ERR, __FILE__": missing or empty required argument 'url'");    if (!service_user)        syslog(LOG_AUTHPRIV|LOG_ERR, __FILE__": missing required argument 'service_user'");    if (!service_password)        syslog(LOG_AUTHPRIV|LOG_ERR, __FILE__": missing required argument 'service_password'");    if (!url || !(*url) || !service_user || !service_password)        return PAM_AUTHINFO_UNAVAIL;    /* get user */    if ((pam_err = pam_get_user(pamh, &user, NULL)) != PAM_SUCCESS)        return (pam_err);    /* get password - TODO why is this retry loop here? */    for (retry = 0; retry < 3; retry++) {        pam_err = pam_get_authtok(pamh, PAM_AUTHTOK, (const char **)&password, NULL);        if (pam_err == PAM_SUCCESS)            break;    }    if (pam_err != PAM_SUCCESS)        return (PAM_AUTH_ERR);    /* strip domain & compare passwords */    stripped_user = strip_domain(user, domain);        if (stripped_user == NULL || pam_restauth_check(url, service_user, service_password,                        group, validate_certificate, stripped_user, password)) {        /* wait a bit */        sleep(2);        pam_err = PAM_AUTH_ERR; // TODO AUTHINFO_UNAVAIL (on hardware failure)    } else {        pam_err = PAM_SUCCESS;    }        if (stripped_user)        free(stripped_user);    return (pam_err);}
开发者ID:RestAuth,项目名称:pam,代码行数:80,


示例28: murmurMessageOutputQString

static void murmurMessageOutputQString(QtMsgType type, const QString &msg) {#ifdef Q_OS_UNIX	if (unixMurmur->logToSyslog) {		int level;		switch (type) {		case QtDebugMsg:			level = LOG_DEBUG;			break;		case QtWarningMsg:			level = LOG_WARNING;			break;		case QtCriticalMsg:			level = LOG_CRIT;			break;		case QtFatalMsg:		default:			level = LOG_ALERT;			break;		}		syslog(level, "%s", qPrintable(msg));		return;	}#endif	char c;	switch (type) {		case QtDebugMsg:			if (! bVerbose)				return;			c='D';			break;		case QtWarningMsg:			c='W';			break;		case QtCriticalMsg:			c='C';			break;		case QtFatalMsg:			c='F';			break;		default:			c='X';	}	QString m= QString::fromLatin1("<%1>%2 %3").arg(QChar::fromLatin1(c)).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")).arg(msg);	if (! qfLog || ! qfLog->isOpen()) {#ifdef Q_OS_UNIX		if (! detach)			fprintf(stderr, "%s/n", qPrintable(m));		else			qlErrors << m;#else		qlErrors << m;#ifndef QT_NO_DEBUG		fprintf(stderr, "%s/n", qPrintable(m));#endif#endif	} else {		if (! qlErrors.isEmpty()) {			foreach(const QString &e, qlErrors) {				qfLog->write(e.toUtf8());				qfLog->write("/n");			}			qlErrors.clear();		}
开发者ID:CarlsonER,项目名称:mumble,代码行数:65,


示例29: daemonize

void daemonize(const char *cmd){    int i, fd0, fd1, fd2;    pid_t pid;    struct rlimit rl;    struct sigaction sa;    /*     * Clear file creation mask.     */    umask(0);    /*     * Get maximum number of file descriptors.     */    if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {        fprintf(stderr, "%s: can’t get file limit/n", cmd);        exit(1);    }    /*     * Become a session leader to lose controlling TTY.     */    if ((pid = fork()) < 0) {        fprintf(stderr, "fork error/n");        exit(1);    } else if (pid != 0) {        // parent        exit(0);    }    setsid();    /*     * Ensure future opens won’t allocate controlling TTYs.     */    sa.sa_handler = SIG_IGN;    sigemptyset(&sa.sa_mask);    sa.sa_flags = 0;    if (sigaction(SIGHUP, &sa, NULL) < 0) {        fprintf(stderr, "can't ignore SIGHUP/n");        exit(0);    }    if ((pid = fork()) < 0) {        fprintf(stderr, "fork error/n");        exit(1);    } else if (pid != 0) {        // parent        exit(0);    }    /*     * Change the current working directory to the root so     * we won’t prevent file systems from being unmounted.     */    if (chdir("/") < 0) {        fprintf(stderr, "%s: can’t change directory to //n", cmd);        exit(0);    }    /*     * Close all open file descriptors.     */    if (rl.rlim_max == RLIM_INFINITY) {        rl.rlim_max = 1024;    }    for (i = 0; i < rl.rlim_max; i++) {        close(i);    }    /*     * Attach file descriptors 0, 1, and 2 to /dev/null.     */    fd0 = open("/dev/null", O_RDWR);    fd1 = dup(0);    fd2 = dup(0);    /*     * Initialize the log file.     */    openlog(cmd, LOG_CONS, LOG_DAEMON);    if (fd0 != 0 || fd1 != 1 || fd2 != 2) {        syslog(LOG_ERR, "unexpected file descriptors %d %d %d", fd0, fd1, fd2);        exit(1);    }}
开发者ID:messense,项目名称:APUE-Learning,代码行数:84,



注:本文中的syslog函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ syslog_action_restricted函数代码示例
C++ sysfs_streq函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。