#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h
> #include <sys/mman.h> #include <pthread.h> pthread_mutex_t* G_mutex;
Create a shared mutex void Init_mutex (void) {int ret; G_mutex must be shared between processes, you cannot achieve a mutex g_mutex= (pthread_mutex_t*) mmap (NULL, sizeof (pthread_mutex_t), prot_read| Prot_write, map_shared|
Map_anonymous,-1, 0);
if (Map_failed==g_mutex) {perror ("mmap");
Exit (1);
}//Set attr properties pthread_mutexattr_t attr;
Pthread_mutexattr_init (&ATTR); Be sure to set the pthread_process_shared//specific reference http://blog.chinaunix.net/u/22935/showart_340408.html Ret=pthread_m
Utexattr_setpshared (&attr,pthread_process_shared);
if (ret!=0) {perror ("Init_mutex pthread_mutexattr_setpshared");
Exit (1); } pthread_mUtex_init (G_mutex, &attr);
int main (int argc, char *argv[]) {Init_mutex ();
int ret;
Char str1[]= "This are child process/r/n";
Char str2[]= "This is Father process/r/n"; int Fd=open ("tmp", o_rdwr| O_creat|
O_trunc, 0666);
if ( -1==FD) {perror ("open");
Exit (1);
} pid_t pid;
Pid=fork ();
if (pid<0) {perror ("fork");
Exit (1);
else if (0==pid) {ret=pthread_mutex_lock (G_mutex);
if (ret!=0) {perror ("Child Pthread_mutex_lock");
Sleep (10);//Whether the test can prevent the parent process from writing write (FD, str1, sizeof (STR1));
Ret=pthread_mutex_unlock (G_mutex);
if (ret!=0) {perror ("Child Pthread_mutex_unlock");
} else {sleep (2);//Ensure that the child process executes first Ret=pthread_mutex_lock (G_mutex);
if (ret!=0) {perror ("Father Pthread_mutex_lock");
Write (fd, str2, sizeof (STR2));
Ret=pthread_mutex_unlock (G_mutex);
if (ret!=0) {perror ("Father Pthread_mutex_unlock");
}} wait (NULL);
Munmap (G_mutex, sizeof (pthread_mutex_t)); }
The contents of the after-run TMP file are:
This are child process
This is Father process