用户空间与内核空间通信一(单播)

/******************************************************************************
 *
 * Description: 
 *   Test the function netlink, the user space route, unicast and multicast. 
 *
 * Kernel space
 *  
 *****************************************************************************/

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <net/sock.h>
#include <linux/netlink.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/err.h>

#define NETLINK_TEST 31
#define THREAD_SLEEP_TIME 1000

MODULE_LICENSE("GPL");

/******************************************************************************
 *
 * Description:
 *   Wake up netlink sock for netlink socket create.
 *
 * Parameter:
 *   sk: netlink socket
 *   len: data length
 *
 * Return:
 *   void
 *
 *****************************************************************************/
void nl_data_ready(struct sock *sk, int len)
{
	wake_up_interruptible(sk->sk_sleep);
}

/******************************************************************************
 *
 * Description:
 *   Netlink testing initialize module. 
 *
 * Parameter:
 *   VOID
 *
 * Return:
 *   NULL
 *
 *****************************************************************************/
void netlink_init(void)
{
	struct sock *nl_sk = NULL;
	struct sk_buff *skb = NULL;
	struct nlmsghdr *nlh = NULL;
	int err = 0;
	u32 pid = 0;

	if ((nl_sk = netlink_kernel_create(NETLINK_TEST, 0, nl_data_ready, 
					THIS_MODULE)) == NULL) {
		printk("netlink_kernel_create failed.\n");
		return;
	}

	/* Recv message from user space */
	skb = skb_recv_datagram(nl_sk, 0, 0, &err);
	nlh = (struct nlmsghdr*)skb->data;
	printk("Recv Netlink message: %s\n", (char*)NLMSG_DATA(nlh));
		
	/* Reply message to user space */
	pid = nlh->nlmsg_pid;
	NETLINK_CB(skb).pid = 0; /* From kernel */
	NETLINK_CB(skb).dst_pid = pid;
	netlink_unicast(nl_sk, skb, pid, MSG_DONTWAIT);

	pid = 0;
	nlh = NULL;				
	sock_release(nl_sk->sk_socket);

	return;
}

/******************************************************************************
 *
 * Description:
 *   Netlink server module initialize function.
 *
 *
 *
 *
 *****************************************************************************/
int  init_module(void)
{
	netlink_init();
	return 0;
}

/******************************************************************************
 *
 * Description:
 *   Netlink server module clearup function.
 *
 *
 *****************************************************************************/
void cleanup_module(void)
{
}

你可能感兴趣的:(kernel,netlink,unicast)