APUE:進程間通信
阿新 • • 發佈:2017-05-28
操作 wait shmdt 半雙工 信號 apue highlight mod 需要
管道
半雙工。一般由父進程創建,用於父子進程間、子進程間通信。匿名,一對一。
// fd[0] 只讀 // fd[1] 只寫 int pipe (int fd[2]);
簡單執行命令行,並讀寫標準輸入輸出。
// 如果 modes == "r",返回標準輸出 // 如果 modes == "w",返回標準輸入 FILE *popen (const char *__command, const char *__modes); int pclose (FILE *__stream);
FIFO(命名管道)
用法:服務端創建一個 FIFO,其它任何進程都可以向其寫入數據,服務端讀到數據後處理。可以一讀多寫。寫數據的大小小於 PIPE_BUF 時為原子操作。
類似文件操作,包括用戶/組/其它人的讀寫執行權限,刪除需要 unlink。
int mkfifo (const char *__path, __mode_t __mode); int mkfifoat (int __fd, const char *__path, __mode_t __mode);
POSIX 信號量
匿名信號量:同一進程不同線程使用。如果需要跨進程,需要將信號量結構體進行內存映射。
命名信號量:可以直接在不同進程中使用。
// 匿名信號量 int sem_init (sem_t *__sem, int __pshared, unsigned int __value) int sem_destroy (sem_t *__sem); // 打開已有信號量,oflag = 0 // 如果需要在信號量不存在時創建,oflag = O_CREAT,且必須指定 mode 的文件訪問權限和 value 信號量初始值(0~SEM_VALUE_MAX) sem_t *sem_open (const char *__name, int __oflag, ... /* mode_t mode, unsigned int value */); int sem_close (sem_t *__sem); // 沒有人使用信號量後,自動刪除 int sem_unlink (const char *__name); // P int sem_wait (sem_t *__sem); int sem_timedwait (sem_t *__restrict __sem, const struct timespec *__restrict __abstime); int sem_trywait (sem_t *__sem); // V int sem_post (sem_t *__sem);
共享存儲
多個進程用相同的 key 使用 sh* 系列函數。
/* The following System V style IPC functions implement a shared memory facility. The definition is found in XPG4.2. */ /* Shared memory control operation. */ extern int shmctl (int __shmid, int __cmd, struct shmid_ds *__buf) __THROW; /* Get shared memory segment. */ extern int shmget (key_t __key, size_t __size, int __shmflg) __THROW; /* Attach shared memory segment. */ extern void *shmat (int __shmid, const void *__shmaddr, int __shmflg) __THROW; /* Detach shared memory segment. */ extern int shmdt (const void *__shmaddr) __THROW;
APUE:進程間通信