- 论坛徽章:
- 0
|
先看一下代码吧
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <unistd.h>
#if defined(__GNU_LIBRARY__) && !defined(_SEM_SEMUN_UNDEFINED)
/* union semun is defined by including <sys/sem.h> */
#else
/* according to X/OPEN we have to define it ourselves */
union semun {
int val; /* value for SETVAL */
struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* array for GETALL, SETALL */
/* Linux specific part: */
struct seminfo *__buf; /* buffer for IPC_INFO */
};
#endif
void LockSetupRead();
void UnlockSetupRead();
void LockSetupWrite();
void UnlockSetupWrite();
int semid;
int main()
{
union semun tInitVal;
pid_t child;
int shmid;
char *pshm;
semid = semget(IPC_PRIVATE, 2, 0x0666 | IPC_CREAT | IPC_EXCL);
if ( semid == -1 )
exit(-1);
tInitVal.val = 1;
semctl(semid, 0, SETVAL, tInitVal);
semctl(semid, 1, SETVAL, tInitVal);
shmid = shmget(IPC_PRIVATE, 1, IPC_CREAT | 0666);
pshm = (char*)shmat(shmid, 0, 0 );
*pshm = 1;
child = fork();
if ( child == -1 )
exit(-1);
else if ( child == 0 )
{
pshm = (char*)shmat(shmid, 0, 0);
//printf("In child process %d, lock write\n", getpid());
LockSetupWrite();
printf("In child process %d, lock write\n", getpid());
printf("In child = %d process: XXXX = %d\n", getpid(), *pshm);
sleep(5);
*pshm = 100;
printf("In child = %d process: XXXX = %d\n", getpid(), *pshm);
UnlockSetupWrite();
printf("Unlock setup write in child process\n");
shmdt(pshm);
exit(0);
}
else
{
LockSetupRead();
printf("In Parent process %d lock read\n", getpid());
printf("In parent process %d : XXXX = %d\n", getpid(), *pshm);
sleep(10);
UnlockSetupRead();
printf("In parent process %d, unlock read: XXXX = %d\n", getpid(), *pshm);
}
semctl(semid, 0, IPC_RMID);
shmdt(pshm);
/*删除共享内存*/
shmctl(shmid, IPC_RMID, NULL);
exit(0);
}
void LockSetupRead()
{
struct sembuf tSemLock;
tSemLock.sem_num = 1;
tSemLock.sem_flg = SEM_UNDO;
tSemLock.sem_op = -1;
semop(semid, &tSemLock, 1);
}
void UnlockSetupRead()
{
struct sembuf tSemUnlock;
tSemUnlock.sem_num = 0;
tSemUnlock.sem_flg = SEM_UNDO;
tSemUnlock.sem_op = 1;
semop(semid, &tSemUnlock, 1);
}
void LockSetupWrite()
{
struct sembuf tSemLock[2];
tSemLock[0].sem_num = 0;
tSemLock[0].sem_flg = SEM_UNDO;
tSemLock[0].sem_op = -1;
tSemLock[1].sem_num = 1;
tSemLock[1].sem_flg = SEM_UNDO;
tSemLock[1].sem_op = -1;
semop(semid, tSemLock, 2);
}
void UnlockSetupWrite()
{
struct sembuf tSemLock[2];
tSemLock[0].sem_num = 0;
tSemLock[0].sem_flg = SEM_UNDO;
tSemLock[0].sem_op = 1;
tSemLock[1].sem_num = 1;
tSemLock[1].sem_flg = SEM_UNDO;
tSemLock[1].sem_op = 1;
semop(semid, tSemLock, 2);
}
该程序实现父子进程共同读写共享内存的一个字节的值。父进程读这个值,子进程写这个值,要求能实现当子进程写的时候父进程既不能读也不能写,而父进程读的时候,子进程不能写。
可是现在的问题是,现在的输出不符合我的要求,不知道什么原因,期待解决方案 |
|