69,337
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#define SIZE 32
#define READ 0
#define WRITE 1
union semun
{
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminfo *__buf;
};
void init_sem(int semid, int array[], int num)
{
int i;
union semun sem;
for (i=0; i<num; i++)
{
sem.val = array[i];
semctl(semid, i, SETVAL, sem);
}
}
void pv(int semid, int num, int op)
{
struct sembuf buf;
buf.sem_num = num;
buf.sem_op = op;
buf.sem_flg = 0;
if (semop(semid, &buf, 1) < 0)
{
exit(0);
}
}
int main (int argc, char *argv[])
{
key_t key;
int shmid, semid, array[] = {0, 1};
char *shmadd;
if ((key = ftok(".",'m')) < 0)
{
perror("fail to ftok");
exit(-1);
}
if ((semid =semget(key, 2, IPC_CREAT | IPC_EXCL | 0666)) < 0)
{
if (EEXIST == errno)
{
if ((semid = semget(key, 2, 0666)) < 0)
{
perror("fail to semget");
exit(-1);
}
}
else
{
perror("fail to semget");
exit(-1);
}
}
else
{
init_sem(semid, array, 2);
}
if ((shmid = shmget(key, SIZE, IPC_CREAT | 0666)) < 0)
{
perror("fail to shmget");
exit(-1);
}
shmadd = (char *)shmat(shmid, NULL, 0);
bzero(shmadd, sizeof(shmadd));
while ( 1 )
{
pv(semid, WRITE, -1);
printf("Please enter msg:\n");
fgets(shmadd, SIZE, stdin);
if (strcmp(shmadd, "quit\n") == 0) break;
pv(shmid, READ, 1);
}
semctl(semid, 0, IPC_RMID);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#define SIZE 32
#define READ 0
#define WRITE 1
union semun
{
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminfo *__buf;
};
void init_sem(int semid, int array[], int num)
{
int i;
union semun sem;
for (i=0; i<num; i++)
{
sem.val = array[i];
semctl(semid, i, SETVAL, sem);
}
}
void pv(int semid, int num, int op)
{
struct sembuf buf;
buf.sem_num = num;
buf.sem_op = op;
buf.sem_flg = 0;
if (semop(semid, &buf, 1) < 0)
{
exit(0);
}
}
int main (int argc, char *argv[])
{
key_t key;
int shmid, semid, array[] = {0, 1};
char *shmadd;
if ((key = ftok(".",'m')) < 0)
{
perror("fail to ftok");
exit(-1);
}
if ((semid =semget(key, 2, IPC_CREAT | IPC_EXCL | 0666)) < 0)
{
if (EEXIST == errno)
{
if ((semid = semget(key, 2, 0666)) < 0)
{
perror("fail to semget");
exit(-1);
}
}
else
{
perror("fail to semget");
exit(-1);
}
}
else
{
init_sem(semid, array, 2);
}
if ((shmid = shmget(key, SIZE, IPC_CREAT | 0666)) < 0)
{
perror("fail to shmget");
exit(-1);
}
shmadd = (char *)shmat(shmid, NULL, 0);
bzero(shmadd, sizeof(shmadd));
while ( 1 )
{
pv(semid,READ, -1);
printf("shmadd msg is: \n");
printf("%s\n",shmadd);
pv(shmid, WRITE, 1);
}
return 0;
}