#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
int main()
{
key_t key, k, shmid;
int ret, semid, i = 0;
struct sembuf op[1];
void *shmptr = (void *) 0;
union semun {
int val;
struct senid_ds *buf;
unsigned short *array;
};
union semun arg;
/* Creating a shared memory */
k = ftok(".", 1);
if (-1 == k) {
perror("\n ftok \n");
return 1;
}
shmid = shmget(k, 1000, IPC_CREAT | 0744);
if (-1 == shmid) {
perror("\n Shared memory creation failed \n");
return 2;
}
shmptr = shmat(shmid, (void *) 0, 0);
if (NULL == shmptr) {
perror("\n Process cant attach to shared memory segment! \n");
return 3;
}
/* Creating semaphore */
key = ftok(".", 4);
if (-1 == key) {
perror("\n ftok \n");
return 4;
}
#if 0
semid = semget(key, 1, IPC_CREAT);
#else
semid = semget(key, 1, 0);
#endif
if (-1 == semid) {
perror("\n Cannot create semaphore \n");
return 5;
}
#if 0
arg.val = 1;
ret = semctl(semid, 0, SETVAL, arg);
printf("\n ret : %d \n", ret);
#endif
op[0].sem_num = 0;
op[0].sem_op = -1;
op[0].sem_flg = SEM_UNDO;
ret = semop(semid, op, 1);
// printf("\n ret : %d semop : %d\n",ret,op[0].sem);
printf("\n Process 1 locked sem1 \n");
/* Do Operation on shared resource */
while (i < 4) {
strcpy((char*) shmptr, "BDC");
printf("\n %s \n", (char *) shmptr);
sleep(2);
printf("\n After sleep \n");
i++;
shmptr++;
}
op[0].sem_op = 1;
ret = semop(semid, op, 1);
printf("\n Process A unlocked sem1 \n");
return 0;
}
我尝试了一个示例程序来锁定共享内存段。我尝试了同一个程序的2个实例。查看信号量是否正确锁定。但是,当process1已经锁定时,上述程序总是允许其他进程使用共享内存。无法确定错误的位置。
答案 0 :(得分:1)
您应该启用IPC_CREAT
语句和按位 - 或者在第3个参数中启用必要但缺少的权限(至少S_IRWXU)。
您应该启用SETVAL
语句将信号量初始化为1,但只根据外部输入执行该语句(即,使用一个参数调用该程序,使其创建信号量并初始化它);否则,程序应该假定信号量已经存在。
您需要检查semop()
来电的返回值。