We are writing programs, the need to synchronize control when the use of the lock to the process of locking control, haha, yesterday to see "UNIX network Programming", which mentions that the program can be used to process the file lock, think it is very interesting, take over to try.
First, we need to know a library function and a struct body: fcntl,struct flock, yes, the function means file control, the structure means the file lock structure. Because, before seeing these two things, the introduction of the Internet is also a lot, here is not to do more introduction, do not understand the classmate Baidu or Google, here, to provide a test program, lock, unlock the idea from "Unix Network Programming"
* * Use File to lock the program/#include <unistd.h> #include <sys/file.h> #include <sys/types.h> #include <sys/ stat.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> static
struct flock lock_it, unlock_it;
static int lock_fd =-1;
void Dlut_lock_init (char *);
void Dlut_lock_wait ();
void Dlut_lock_release (); int main (int argc, char **argv, char **environ) {dlut_lock_init ("test").
XXXXXX ");
Dlut_lock_wait ();
if (!fork ()) {dlut_lock_wait ();
printf ("Hello, this are child%d\n", Getpid ());
Sleep (3);
Dlut_lock_release ();
Exit (0);
printf ("Hello, this is parent%d\n", Getpid ());
Dlut_lock_release ();
Sleep (1);
return 0;
} void Dlut_lock_init (char *path_name) {char lock_file[1024];
Char file_name[1024];
strcpy (Lock_file, path_name);
strcpy (file_name, Mktemp (lock_file)); LOCK_FD = open (file_name, O_RDWR |
O_creat, 0666);
Unlink (Lock_file);
Lock_it.l_type = F_wrlck; Lock_it.l_whence = =K_set;
Lock_it.l_start = 0;
Lock_it.l_len = 0;
Unlock_it.l_type = F_unlck;
Unlock_it.l_whence = Seek_set;
Unlock_it.l_start = 0;
Unlock_it.l_len = 0;
} void Dlut_lock_wait () {int rc;
while (rc = Fcntl (LOCK_FD, F_SETLKW, &lock_it)) < 0) {if (errno = = eintr) continue;
else {perror ("Fcntl error ...");
Exit (1);
} return;
} void Dlut_lock_release () {if (Fcntl (LOCK_FD, F_SETLKW, &unlock_it)) {perror ("Fcntl error");
Exit (2);
} return;
}
I mean, the parent process gets the file lock first, and then prints a line of words before the subprocess can print a line of words.