input.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/sem.h>
union semnum {
int val;
};
int main(int argc, char const *argv[])
{
key_t key = ftok("./semop.c", 'a');
if (key < 0)
{
perror("ftok err:");
return -1;
}
int shmid = shmget(key, 128, IPC_CREAT | IPC_EXCL | 0666);
if (shmid <= 0)
{
if (errno == EEXIST)
{
shmid = shmget(key, 128, 0666);
}
else
{
perror("shmget err:");
return -1;
}
}
char *q = (char *)shmat(shmid, NULL, 0);
if (q == (void *)-1)
{
perror("shmat err:");
return -1;
}
int semid = semget(key, 1, IPC_CREAT | IPC_EXCL | 0666);
if (semid <= 0)
{
if (errno == EEXIST)
{
semid = semget(key, 1, 0666);
}
else
{
perror("semget err:");
return -1;
}
}
else
{
union semnum p;
p.val = 0;
semctl(semid, 0, SETVAL, p);
}
while (1)
{
scanf("%s", q);
struct sembuf sem;
sem.sem_num = 0;
sem.sem_op = +1; //V释放
sem.sem_flg = 0; //阻塞
semop(semid, &sem, 1);
if (!strcmp(q, "quit"))
{
break;
}
}
return 0;
}
output.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/sem.h>
#include <sys/wait.h>
union semnum {
int val;
};
int main(int argc, char const *argv[])
{
key_t key = ftok("./semop.c", 'a');
if (key < 0)
{
perror("ftok err:");
return -1;
}
int shmid = shmget(key, 128, 0666);
if (shmid <= 0)
{
perror("shmget err:");
return -1;
}
struct msg
{
char buf[32];
};
struct msg *q = (struct msg *)shmat(shmid, NULL, 0);
if (q == (void *)-1)
{
perror("shmat err:");
return -1;
}
int semid = semget(key, 1, IPC_CREAT | IPC_EXCL | 0666);
if (semid <= 0)
{
if (errno == EEXIST)
{
semid = semget(key, 1, 0666);
}
else
{
perror("semget err:");
return -1;
}
}
else
{
union semnum p;
p.val = 0;
semctl(semid, 0, SETVAL, p);
}
while (1)
{
struct sembuf sem;
sem.sem_num = 0;
sem.sem_op = -1; //P操作
sem.sem_flg = 0; //阻塞
semop(semid, &sem, 1);
if (!strcmp(q->buf, "quit"))
{
shmdt(q);
shmctl(shmid, IPC_RMID, NULL);
break;
}
printf("buf:%s\n", q->buf);
}
return 0;
}
hq@Ubuntu:~/23022/c/yun/day14$ gcc input.c -o input
hq@Ubuntu:~/23022/c/yun/day14$ gcc output.c -o output
hq@Ubuntu:~/23022/c/yun/day14$ ./input
123
qwe
quit
hq@Ubuntu:~/23022/c/yun/day14$
hq@Ubuntu:~/23022/c/yun/day14$ ./output
buf:123
buf:qwe
hq@Ubuntu:~/23022/c/yun/day14$