当前位置: 技术问答>linux和unix
在linux下,用共享内存来实现进程间的数据交互,请问如何实现同步?(这些进程没有父子关系)
来源: 互联网 发布时间:2016-02-19
本文导语: 听说用信号量(sem_init这一套)可以,但不知道怎么正确使用,查资料后有人说在linux下信号量不能实现进程间同步,了解不多,希望各位高手多多指点,最好能给个例子,谢谢! | server.c #include #inc...
听说用信号量(sem_init这一套)可以,但不知道怎么正确使用,查资料后有人说在linux下信号量不能实现进程间同步,了解不多,希望各位高手多多指点,最好能给个例子,谢谢!
|
server.c
#include
#include
#define SEGSIZE 1024
#define READTIME 1
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
} arg;
//生成信号量
int sem_creat(key_t key)
{
union semun sem;
int semid;
sem.val = 0;
semid = semget(key,1,IPC_CREAT|0666);
if (-1 == semid){
printf("create semaphore errorn");
exit(-1);
}
semctl(semid,0,SETVAL,sem);
return semid;
}
//删除信号量
void del_sem(int semid)
{
union semun sem;
sem.val = 0;
semctl(semid,0,IPC_RMID,sem);
}
//p
int p(int semid)
{
struct sembuf sops={0,+1,IPC_NOWAIT};
return (semop(semid,&sops,1));
}
//v
int v(int semid)
{
struct sembuf sops={0,-1,IPC_NOWAIT};
return (semop(semid,&sops,1));
}
int main()
{
key_t key;
int shmid,semid;
char *shm;
char msg[7] = "-data-";
char i;
struct semid_ds buf;
key = ftok("/",0);
shmid = shmget(key,SEGSIZE,IPC_CREAT|0604);
if (-1 == shmid){
printf(" create shared memory errorn");
return -1;
}
shm = (char *)shmat(shmid,0,0);
if (-1 == (int)shm){
printf(" attach shared memory errorn");
return -1;
}
semid = sem_creat(key);
for (i = 0;i