Linux下的多進程間共用資源的互斥訪問

來源:互聯網
上載者:User
#include    <stdio.h>    #include    <stdlib.h>    #include    <unistd.h>    #include    <fcntl.h>    #include    <sys/mman.h>    #include    <pthread.h>    pthread_mutex_t* g_mutex;    //建立共用的mutex    void init_mutex(void)    {        int ret;        //g_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);        }                    //設定attr的屬性        pthread_mutexattr_t attr;        pthread_mutexattr_init(&attr);        //一定要設定為PTHREAD_PROCESS_SHARED        //具體可以參考http://blog.chinaunix.net/u/22935/showart_340408.html        ret=pthread_mutexattr_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 is 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);//測試是否能夠阻止父進程的寫入            write(fd, str1, sizeof(str1));            ret=pthread_mutex_unlock(g_mutex);              if( ret!=0 )            {                perror("child pthread_mutex_unlock");            }           }        else    {            sleep(2);//保證子進程先執行             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));    }

運行後tmp檔案內容為:

this is child process

this is father process

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.