要求在共享内存中存入字符串 “1234567”。A进程循环打印字符串,B进程循环倒置字符串,要求结果不允许出现乱序:
输出进程
#include <head.h>
int main(int argc, const char* argv[])
{
// 创建key值
key_t key = ftok("/home/y", 1);
if (key < 0)
PRINT_ERR("ftok");
// 创建共享内存
int shmid = shmget(key, 128, IPC_CREAT | 0664);
if (shmid < 0)
PRINT_ERR("shmget");
printf("shmid=%d\n", shmid);
// 映射共享内存
void* addr = shmat(shmid, NULL, 0);
if ((void*)-1 == addr)
PRINT_ERR("shmat");
// 创建信号灯集
int semid = semget(key, 2, IPC_CREAT | 0664);
if (semid < 0)
PRINT_ERR("semget");
// 初始化信号灯集
unsigned short array[2] = { 1, 0 };
if (semctl(semid, 0, SETALL, array) < 0)
PRINT_ERR("semctl");
struct sembuf sops0, sops1;
sops0.sem_num = 0;
sops0.sem_op = -1;
sops0.sem_flg = 0;
sops1.sem_num = 1;
sops1.sem_op = 1;
sops1.sem_flg = 0;
char* str = (char*)addr;
strcpy(str, "hello world");
while (1) {
if (semop(semid, &sops0, 1) < 0) // P 0号灯
PRINT_ERR("semop");
puts(str);
if (semop(semid, &sops1, 1) < 0) // V 1号灯
PRINT_ERR("semop");
}
return 0;
}
倒置进程
#include <head.h>
void invert(char* str)
{
int i = 0;
int j = strlen(str) - 1;
char temp;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}
int main(int argc, const char* argv[])
{
// 创建key值
key_t key = ftok("/home/y", 1);
if (key < 0)
PRINT_ERR("ftok");
// 创建共享内存
int shmid = shmget(key, 128, IPC_CREAT | 0664);
if (shmid < 0)
PRINT_ERR("shmget");
printf("shmid=%d\n", shmid);
// 映射共享内存
void* addr = shmat(shmid, NULL, 0);
if ((void*)-1 == addr)
PRINT_ERR("shmat");
// 创建信号灯集
int semid = semget(key, 2, IPC_CREAT | 0664);
if (semid < 0)
PRINT_ERR("semget");
// 初始化信号灯集
unsigned short array[2] = { 1, 0 };
if (semctl(semid, 0, SETALL, array) < 0)
PRINT_ERR("semctl");
struct sembuf sops0, sops1;
sops0.sem_num = 0;
sops0.sem_op = 1;
sops0.sem_flg = 0;
sops1.sem_num = 1;
sops1.sem_op = -1;
sops1.sem_flg = 0;
char* str = (char*)addr;
while (1) {
if (semop(semid, &sops1, 1) < 0) // P 1号灯
PRINT_ERR("semop");
invert(str);
if (semop(semid, &sops0, 1) < 0) // V 0号灯
PRINT_ERR("semop");
}
return 0;
}