The following describes how to use the flag and how to operate a shared resource with only one execution thread at any time. First, we will introduce the model, first, use C to write a test application and create five processes to open a device. If no flag is added, the five processes are enabled at the same time and closed after use. After the flag is added, only one process can be opened at a time, other processes can be operated only after the device is used. The template uses the template described last time.
Test the C code and create five processes to open the device at the same time.
# Include <stdio. h> # include <fcntl. h> # include <sys/types. h> # include <unistd. h> int main (int * argc, char ** argv) {pid_t PID; int FS, I; for (I = 0; I <5; I ++) {pid = fork (); If (PID <0) {printf ("fork error! \ N "); Return-1;} else if (pid = 0) {/* the sub-process uses the device */fs = open ("/dev/moduledev60 ", o_rdwr); If (FS <0) {printf ("Open fail \ n"); Return-1;} printf ("open by PID: % d \ n ", getpid (); usleep (2000); close (FS); printf ("close by PID: % d \ n", getpid (); Return 0 ;}} sleep (1); Return 0 ;}
Driver Modification
# Include <Linux/init. h> # include <Linux/kernel. h >#include <Linux/kdev_t.h> # include <Linux/err. h> # include <Linux/cdev. h> # include <Linux/Fs. h> # include "fileops. H "# include <ASM/uaccess. h> # include <Linux/delay. h> # include "Linux/semaphore. H "struct semaphore SEM;/*** call */INT fileops_init (void) {sema_init (& SEM, 1); Return 0;} during loading Initialization ;} /*** call the release function when the module is detached */void fileops_destroy (void) {}int fileops_open (struct inode * inode, struct file * filp) {If (down_interruptible (& SEM) Return-1; printk (kern_alert "fileops_open \ n"); Return 0;} int fileops_release (struct inode * inode, struct file * filp) {printk (kern_alert "fileops_release \ n"); up (& SEM); Return 0 ;}
Modify main. c
struct file_operations ops={ .owner=THIS_MODULE, .open=fileops_open, .release=fileops_release};
If no flag is added, the test result device is enabled by multiple processes at the same time.
[root@localhost ctest]# ./main;open by pid:5237 open by pid:5239 open by pid:5235 open by pid:5238 open by pid:5236 close by pid:5237 close by pid:5239 close by pid:5235 close by pid:5238 close by pid:5236
Enable devices one by one after the flag is added
[root@localhost ctest]# ./main;open by pid:8618 close by pid:8618 open by pid:8620 close by pid:8620 open by pid:8617 close by pid:8617 open by pid:8621 close by pid:8621 open by pid:8619 close by pid:8619