日期:2014-05-16  浏览次数:20624 次

进程间共享的Posix mutex的锁定状态能否被子进程继承?
APUE中有这样一句话:
"By inheriting a copy of the address space, the child also inherits the state of every mutex, readerwriter lock, and condition variable from the parent process."

说父进程中的mutex的锁定状态会被子进程继承,但是没有提及具有进程间共享属性的mutex是否也遵守这一规则。
写了个小程序验证一下(程序中省略了错误检查)。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main(void)
{
    pid_t pid;
    int   mid;
    int   bCreate = 0;      // 是否新建mutex
    key_t key = 0x12341234;

    pthread_mutex_t *mut;
    pthread_mutexattr_t attr;

    // shared memory
    mid = shmget(key, 0, 0);

    if( mid == -1 )         // 共享内存不存在,新建
    {
        bCreate = 1;
        mid = shmget(key, 64, IPC_CREAT | 0666);
    }
    mut = (pthread_mutex_t *) shmat(mid, 0, 0);

    if( bCreate == 1 )      // 初始化mutex,设置为进程间共享
    {
        pthread_mutexattr_init(&attr);
        pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
        pthread_mutex_init(mut, &attr);
        pthread_mutexattr_destroy(&attr);
    }

    printf("lock\n");
    pthread_mutex_lock(mut);

    printf("fork\n");
    pid = fork();
    if( pid == 0 )          // 子进程无限期睡眠
    {
        while( 1 ) pause();
        exit(0);
    }

    printf("unlock\n");
    pthread_mutex_unlock(mut);

    printf("lock again\n");
    pthread_mutex_lock(mut);
    printf("over\n");

    pthread_mutex_destroy(mut);
    kill(pid, SIGKILL);     // 杀死子进程
    return(0);
}


1、初次执行时,程序会创建共享内存,初始化mutex。结果是无停顿执行完毕。
   --看来父进程中的锁定状态没有被子进程继承,否则父进程的lock again不能完成。
2、再次执行时,程序阻塞在第一个lock的位置
   --UNP第二卷中,说“Posix mutex具有随进程的持续性”,看来也不适用于具有进程间共享属性的mutex

经验不足,不知道理解的对不对,求证一下。