#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc,char *argv[]){
//pthread_mutex_init,set process_shared
pthread_mutex_t lock;
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setpshared(&mutexattr,PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&lock,&mutexattr);
pid_t pid;
int status;
pid = fork();
if(pid < 0)
{
perror("fork is error\n");
exit(EXIT_FAILURE);
}else if(pid == 0){
//child process get the mutex lock
pthread_mutex_lock(&lock);
//know who first get the lock
printf("child lock:pid = %d,ppid = %d\n",getpid(),getppid());
sleep(5);
pthread_mutex_unlock(&lock);
printf("child unlock:pid = %d,ppid = %d\n",getpid(),getppid());
}else{
//father process get the mutex lock
pthread_mutex_lock(&lock);
//know who first get the lock
printf("father lock:pid = %d,ppid = %d\n",getpid(),getppid());
sleep(5);
pthread_mutex_unlock(&lock);
printf("father unlock:pid = %d,ppid = %d\n",getpid(),getppid());
wait(&status);
if(WIFEXITED(status))
{
printf("child is finish,status: %s\n",WEXITSTATUS(status));
}
if(WIFSIGNALED(status))
{
printf("child is finish,status: %s\n",WTERMSIG(status));
}
}
return 0;
}
此代码显示:父进程和子进程同时获得一个锁,但是描述一个进程的pthread_mutexattr_setpshared
函数获得一个锁,该代码是错误的。
The pthread_mutexattr_getpshared() function shall obtain the value of the process-shared attribute from the attributes object referenced by attr. The pthread_mutexattr_setp_shared() function shall set the process-shared attribute in an initialized attributes object referenced by attr.
The process-shared attribute is set to PTHREAD_PROCESS_SHARED to permit a mutex to be operated upon by any thread that has access to the memory where the mutex is allocated,
even if the mutex is allocated in memory that is shared by multiple processes. If the process-shared attribute is PTHREAD_PROCESS_PRIVATE, the mutex shall only be operated upon
by threads created within the same process as the thread that initialized the mutex; if threads of differing processes attempt to operate on such a mutex, the behavior is unde
fined. The default value of the attribute shall be PTHREAD_PROCESS_PRIVATE
这是因为它们不share锁所驻留的内存:在
fork
之后,每个进程都有其自己的(堆栈)内存副本。要使此工作有效,您必须先
mmap(..., MAP_SHARED, ...)
内存,在该内存中初始化互斥锁,然后fork
。