第一题: 由于共享内存没有同步,想办法搞定共享内存的同步问题
第二题: 使用第一题作用已经实现的共享内存,去做2个终端之间的互相聊天
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
typedef struct shmbuf
{
char t[128];
int flag;
} shm_t, *shm_p;
void *taskr2(void *arg)
{
key_t key = ftok("./hw", 1);
int shmid = shmget(key, sizeof(shm_t), IPC_CREAT | 0666);
shm_p addr = shmat(shmid, 0, 0);
while (1)
{
while (1)
{
if (addr->flag == 0)
break;
}
printf("读取:%s\n", addr->t);
// sleep(1);
addr->flag = 1;
}
}
int main(int argc, const char *argv[])
{
key_t key = ftok("./hw", 1);
int shmid = shmget(key, sizeof(shm_t), IPC_CREAT | 0666);
shm_p addr = shmat(shmid, 0, 0);
pthread_t r2;
pthread_create(&r2, 0, taskr2, 0);
pthread_detach(r2);
while (1)
{
while (1)
{
if (addr->flag == 1)
break;
}
printf("请输入:");
scanf("%255s", addr->t);
while (getchar() != 10)
;
// sleep(1);
addr->flag = 0;
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
typedef struct shmbuf
{
char t[128];
int flag;
} shm_t, *shm_p;
void *taskw2(void *arg)
{
key_t key = ftok("./hw", 1);
int shmid = shmget(key, sizeof(shm_t), IPC_CREAT | 0666);
shm_p addr = shmat(shmid, 0, 0);
while (1)
{
while (1)
{
if (addr->flag == 1)
break;
}
printf("请输入:");
scanf("%255s", addr->t);
while (getchar() != 10)
;
// sleep(1);
addr->flag = 0;
}
}
int main(int argc, const char *argv[])
{
key_t key = ftok("./hw", 1);
int shmid = shmget(key, sizeof(shm_t), IPC_CREAT | 0666);
shm_p addr = shmat(shmid, 0, 0);
pthread_t w2;
pthread_create(&w2, 0, taskw2, 0);
pthread_detach(w2);
while (1)
{
while (1)
{
if (addr->flag == 0)
break;
}
printf("读取:%s\n", addr->t);
// sleep(1);
addr->flag = 1;
}
return 0;
}