Linux下的多程序間共享資源的互斥訪問

2021-09-01 02:30:16 字數 1316 閱讀 7328

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!

#include

#include

#include

#include

#include

#include

pthread_mutex_t* g_mutex;  //建立共享的mutex 

void

init_mutex

(void)

//設定attr的屬性 

pthread_mutexattr_t attr;      pthread_mutexattr_init(&attr);      //一定要設定為pthread_process_shared 

//具體可以參考      ret=pthread_mutexattr_setpshared(&attr,pthread_process_shared);      if( ret!=0 )            pthread_mutex_init(g_mutex, &attr);  }  int

main

(int argc, char *argv)

pid_t pid;      pid=fork();      if( pid<0 )            else

if( 0==pid )                sleep(10);//測試是否能夠阻止父程序的寫入          write(fd, str1, sizeof(str1));          ret=pthread_mutex_unlock(g_mutex);            if( ret!=0 )                   }      else                write(fd, str2, sizeof(str2));          ret=pthread_mutex_unlock(g_mutex);            if( ret!=0 )                               }      wait(null);      munmap(g_mutex, sizeof(pthread_mutex_t));  }

執行後tmp檔案內容為:this is child processthis is father process給我老師的人工智慧教程打call!

程序間 對共享資源的訪問 互斥 機制

分類 linux程式設計 2010 05 04 19 21 4291人閱讀收藏 舉報linux null測試 把源 執行一遍就知道了 cpp view plain copy include include include include include include pthread mutex t...

fork後父子程序共享資源

unix環境高階程式設計中8.3節中說,子程序是父程序的副本。例如,子程序獲得父程序資料空間 堆和棧的副本。注意,這是子程序所擁有的副本。父程序和子程序並不共享這些儲存空間部分。父程序和子程序共享正文段。書中還預留了例子說明子程序對變數所做的改變並不影響父程序中該變數的值。fork.c 父子程序共享...

Linux與Windows共享資源NFS

nfs network file system,網路檔案系統,是在linux系統間實現磁碟檔案共享的一種方法,它支援應用程式在客戶端通過網路訪問位於伺服器磁碟中資料的一種檔案系統協議。同時可以在windows系統上安裝nfs client和server來實現與linux系統資源的共享。1 linux...