我想同步兩個處理程序讀取和寫入共享內存。這裏是a_process.c
:如何在c上使用posix命名信號與linux上兩個進程之間的共享內存?
#include <fcntl.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#define SHM_PATH "/instant_messaging"
#define SHM_SIZE 50
#define SEM_PATH "/sem_instant_messaging"
char *sendbuff;
int main()
{
//sahred memory setting
//shm_unlink(SHM_PATH);
int shmfd;
shmfd = shm_open(SHM_PATH, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG);
if (shmfd < 0) {
perror("In shm_open()");
exit(1);
}
int shm_size = SHM_SIZE;
ftruncate(shmfd, shm_size);
sendbuff = (char*) mmap(NULL, shm_size, PROT_READ | PROT_WRITE,
MAP_SHARED, shmfd, 0);
if (sendbuff == NULL) {
perror("In mmap()");
exit(1);
}
//semaphore setting
sem_unlink(SEM_PATH);
sem_t * sem1;
sem1 = sem_open(SEM_PATH, O_CREAT, S_IRUSR | S_IWUSR, 1);
printf("before while\n");
//setmemshr();
//setsem();
while (1) {
int status = sem_wait(sem1);
if (status != 0)
{
perror("in sem_wait");
}
printf("after wait\n");
printf("%s\n",sendbuff);
scanf("%s",sendbuff);
sem_post(sem1);
//sleep(3);
}
}
這裏是b_process.c
:
#include <fcntl.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#define SHM_PATH "/instant_messaging"
#define SHM_SIZE 50
#define SEM_PATH "/sem_instant_messaging" //dddddddddd
char *sendbuff;
int main()
{
//sahred memory setting
//shm_unlink(SHM_PATH);
int shmfd;
shmfd = shm_open(SHM_PATH, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG);
if (shmfd < 0) {
perror("In shm_open()");
exit(1);
}
int shm_size = SHM_SIZE;
ftruncate(shmfd,shm_size);
sendbuff = (char*) mmap(NULL, shm_size, PROT_READ | PROT_WRITE,
MAP_SHARED, shmfd, 0);
if (sendbuff == NULL) {
perror("In mmap()");
exit(1);
}
//semaphore setting
sem_unlink(SEM_PATH);
sem_t *sem1;
sem1 = sem_open(SEM_PATH, O_CREAT, S_IRUSR | S_IWUSR, 1);
while (1) {
printf("before wait %d\n", *sem1);
int status = sem_wait(sem1);
if (status != 0)
{
perror("in sem_wait");
}
printf("after wait %d\n", *sem1);
printf("%s", sendbuff);
scanf("%s", sendbuff);
sem_post(sem1);
}
}
我已經花了很多的時間調試這和閱讀手冊頁,但它看來,雖然共享內存的工作原理和信號後,等待在每個進程的地址空間內工作,這兩個進程不會影響另一個在共享內存區域中看到的數據。
有沒有人看到我失蹤?
它對我來說看起來不錯,你爲什麼說它不影響其他過程中的價值? –
是的......這樣的東西最好在它所沒有的系統/環境中進行測試和調試。 OP,那將是你的。 –
@先生,當我打sem_wait(sem1);它應該阻止另一個進程,但它並沒有,儘管* sem1的值從1遞減到0 – mohammed