天天看點

net-snmp 線程安全

#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/select.h>
#include <pthread.h>
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/session_api.h>


 struct thread_info {
	pthread_t id;
	int num;
	char *sw_ip;
	char *community;
	char *oid;
};

int sess_callback(int operation, struct snmp_session *sp, int reqid,
                 struct snmp_pdu *pdu, void *magic)
{
	printf("hello snmp callback. [%d]\n", (int)magic);
	return 0;
}

static void deal_snmp(struct thread_info *data)
{
	struct snmp_session sess;
	void *handle;

	snmp_sess_init(&sess);
	sess.retries = 3;
	sess.peername = data->sw_ip;

	sess.version = SNMP_VERSION_2c;
        sess.community = (char *)data->community;
        sess.community_len = strlen(data->community);

	sess.callback = sess_callback;
	sess.callback_magic = (void *)data->num;

	handle = snmp_sess_open(&sess);
	if (!handle){
		printf("snmp sess open failed.\n");
		return;
	}

	struct snmp_pdu *req = snmp_pdu_create(SNMP_MSG_GETBULK);
	req->non_repeaters = 0;
	req->max_repetitions = 30;

	oid testOid[MAX_OID_LEN];
	size_t testOidLen = MAX_OID_LEN;
	read_objid(data->oid, testOid, &testOidLen);
	snmp_add_null_var(req, testOid, testOidLen);

	
	if(snmp_sess_send(handle, req))
	{
		printf("snmp send success. [%d]\n", data->num);
	}
	else
	{
		printf("snmp send failed.\n");
		snmp_free_pdu(req);
		goto exit;
	}

	int fds = 0, block = 0, number;
	fd_set fdset;
	struct timeval timeout;
	FD_ZERO(&fdset);
	timeout.tv_sec = 3;
	
	number = snmp_sess_select_info(handle, &fds, &fdset, &timeout, &block);
	if(!number)
        {
		printf("select info error.\n");
		goto exit;
	}

	timeout.tv_sec = 3;
	fds = select(fds, &fdset, NULL, NULL, &timeout);
	if(fds > 0)
        {
		printf("read success. [%d]\n", data->num);
		snmp_sess_read(handle, &fdset);
	}
	else
	{
		printf("timeout.\n");
		snmp_sess_timeout(handle);
	}

exit:
	snmp_sess_close(handle);
}


int main(int argc, char *argv[])
{
	int i;

	if (argc < 3)
	{
		printf("%s sw_ip community oid\n", argv[0]);
		return -1;
	}

	printf("%s %s %s %s\n", argv[0], argv[1], argv[2], argv[3]);
	
	struct thread_info info[10];
	for (i=0;i<10;i++)
	{
		info[i].num = i+1;
		info[i].sw_ip = argv[1];
		info[i].community = argv[2];
		info[i].oid = argv[3];
	
		pthread_create(&info[i].id, NULL, deal_snmp, &info[i]);	
	}

	for (i=0;i<10;i++)
	{
		pthread_join(info[i].id, NULL);
	}

	return 0;
}

           

繼續閱讀