fasync异步通信出问题了 急急急
void input_handler(){
char data;
int len;
//读取并输出STDIN_FILENO上的输入
len = read(fd, &data, MAX_LEN);
data = 0;
printf("input available:%s\n", data);
}
main()
{
int oflags;
//启动信号驱动机制
fd=open("dev/chrdev",O_RDWR);
signal(SIGIO, input_handler);
fcntl(fd, F_SETOWN, getpid());
printf("a\n");
oflags = fcntl(STDIN_FILENO, F_GETFL);
printf("b\n");
fcntl(STDIN_FILENO, F_SETFL, oflags | FASYNC);
printf("c\n");
}
驱动里的相关代码
static ssize_t chardev_read(struct file *filp, char __user *buff, size_t count, loff_t *f_pos)
{
int num=0;
if (down_interruptible(&sem))
goto err;
count = strlen(buffer);
num=copy_to_user(buff, buffer, count);
up(&sem);
return count;
err:
return -ERESTARTSYS;
}
static ssize_t chardev_write(struct file *filp, const char __user *buff, size_t count, loff_t *f_pos)
{
int num=0;
if (down_interruptible(&sem))
goto err;
memset(buffer, '\0', sizeof(buffer));
num=copy_from_user(buffer, buff, count);
up(&sem);
if (async)
kill_fasync(&async, SIGIO, POLL_IN);
printk("have started a signal\n");
return count;
err:
return -ERESTARTSYS;
}
static int chardev_fasync(int fd, struct file *filp, int mode)
{
return fasync_helper(fd, filp, mode, &async);
}
static int chardev_release(struct inode *inodp, struct file *filp)
{
return chardev_fasync(-1, filp, 0);
}
不明白上层执行后, input_handler()函数会连续执行很多次,以后在运行这个程序, input_handler()都不会被条用了,除非关闭SHELL终端,然后重新打开SHELL终端,就是说子SHELL终端打开后,只有第一次运行这个程序是 input_handler()会被调用而且是连续调用很多次,或者无数次,。
打印出来的c这条语句也会连续执行两次,这是怎么回事,而且static int chardev_release(struct inode *inodp, struct file *filp)
{
return chardev_fasync(-1, filp, 0);
}
return chardev_fasync(-1, filp, 0);这个是起什么作用,为什么会把这个函数放在chardev_release()函数里 return chardev_fasync(-1, filp, 0);是用来告诉内核,这个异步通知我用完了,内核会在异步链表头中把这个异步通知删掉。
你的main函数执行完毕后,就退出吧,自我感觉一遍都不会打印出来。这样写,比较的合理吧。
void input_handler(int signum)
{
printf("receive a signal from globalfifo,signalnum:%d\n",signum);
}
main()
{
int fd, oflags;
fd = open("/dev/globalfifo", O_RDWR, S_IRUSR | S_IWUSR);
if (fd !=- 1) {
printf("-----------signal-----in-------\n");
/* Æô¶¯ÐźÅÇý¶¯»úÖÆ */
signal(SIGIO, input_handler); /* ÈÃinput_handler()ŽŠÀíSIGIOÐźŠ*/
printf("-----------getpid()------------\n");
fcntl(fd, F_SETOWN, getpid());
printf("-----------fcntl(fd, F_GETFL);------------\n");
oflags = fcntl(fd, F_GETFL);
printf("-----------fcntl(fd, F_SETFL, oflags | FASYNC);----in------\n");
fcntl(fd, F_SETFL, oflags | FASYNC);
printf("-----------fcntl(fd, F_SETFL, oflags | FASYNC);---out---------\n");
while(1) {
sleep(100);
}
} else {
printf("device open failure\n");
}
}
页:
[1]