谁给个进程间共享内存同步的例子,多谢
rt
另,进程间同步可以用pthread_mutex_lock/pthread_mutex_unlock来处理么,原因是什么
------解决方案--------------------不行.那个是线程间的操作...
指同一进程中的...
进程间的用IPC机制...一时找不到例子,你在网上搜搜吧...
------解决方案--------------------LinuxThreads有 "一对一 "模型,一个线程实体对应一个核心轻量级进程,而线程之间的管理在核外函数库中实现。
另外,怀疑楼主说的进程同步应该指的就是线程同步,LinuxThreads中的线程同步很大程度上是建立在信号基础上的,所以用pthread_mutex_lock/pthread_mutex_unlock应该是可以的,大胆尝试....
------解决方案--------------------服务器端:
//服务器
#include <sys/sem.h>
#include <sys/ipc.h>
#define SEGSIZE 1024
#define READTIME 1
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// key_t key:标识信号量的关键字
// semid:信号量的ID
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/
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 =1;
semid = semget(key,1,IPC_CREAT|0666);
if (-1 == semid)
{
printf( "create semaphore error\n ");
exit(-1);
}
semctl(semid,1,SETVAL,sem);
return semid;
}
//删除信号量
void del_sem(int semid)
{
union semun sem;
sem.val = 0;
semctl(semid,0,IPC_RMID,sem);
}
// </P < p>
//p
int p(int semid)
{
struct sembuf sops={0,+1,SEM_UNDO};
return (semop(semid,&sops,1));
}
//v
int v(int semid)
{
struct sembuf sops={0,-1,SEM_UNDO};
return (semop(semid,&sops,1));
}
int main()
{
key_t key;
int shmid,semid;
char *shm;
char msg[7] = "-data- ";
struct semid_ds buf;
key = ftok( "/home/jiangxd/Project/aaaaa ",1);
shmid = shmget(key,SEGSIZE,IPC_CREAT|0666);
if (-1 == shmid)
{
printf( " create shared memory error\n ");
return -1;
}
shm = (char *)shmat(shmid,0,0);
if (-1 == (int)shm)
{
printf( " attach shared memory error\n ");
return -1;
}
int key2 = ftok( "/home/jiangxd/Project/aaaaa " , 0);
semid = sem_creat(key2);
int j = 10;
memcpy(shm , &j , sizeof(int));
p(semid);
int i ;
for(i = 0 ; i < 20 ; i++)
{
//在读内存之前应该先V,以免client读到旧数;
int a;
v(semid);
memcpy(&a , shm , sizeof(int));
a++;
sleep(1);
memcpy(shm , &a , sizeof(int));
p(semid);
}
memcpy(&j , shm , sizeof(int));
printf( "j=%d\n " , j);
//
//
msg[5] = '0 ' + i;
//memcpy(shm,msg,sizeof(msg));
//
shmdt(shm);
shmctl(shmid,IPC_RMID,&buf);
del_sem(semid);
return 0;
//gcc -o shm shm.c -g
}
客户端:
#include <sys/sem.h>
#include <time.h>
#include <sys/ipc.h>
#define SEGSIZE 1024
#define READTIME 1
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
} arg;
// 打印程序执行时间
void out_time(void)
{
static long start = 0;
time_t tm;
if (0 == start)
{
tm = time(NULL);
start = (long)tm;
printf( " now start ...\n ");
}
pri