#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <string.h>
int main(int argc, char* argv[])
{
int running = 1;
int shid;
int semid;
int value;
int read_num;
FILE *stream;
char* sharem=NULL;
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_flg = SEM_UNDO;
if((semid = semget((key_t)123456,1,0666|IPC_CREAT))==-1)
{
perror("semget");
exit(EXIT_FAILURE);
}
if(semctl(semid,0,SETVAL,0)==-1)
{
printf("sem init error");
if(semctl(semid,0,IPC_RMID,0)!=0)
{
perror("semctl");
exit(EXIT_FAILURE);
}
exit(EXIT_FAILURE);
}
shid = shmget((key_t)654321,(size_t)30,0600|IPC_CREAT);
if(shid == -1)
{
perror("shmget");
exit(EXIT_FAILURE);
}
sharem = shmat(shid,NULL,0);
if(sharem==NULL)
{
perror("shmat");
exit(EXIT_FAILURE);
}
stream = fopen("data.in","r");
while(running)
{
// printf("write data operate\n");
// while((semctl(semid,0,GETVAL))==1);
if((value=semctl(semid,0,GETVAL))==0)
{
// if((read_num = fread(sharem,20,1,stream))==0)
// running--;
if(fscanf(stream,"%s",sharem)!=EOF)
{
printf("%s\n",sharem);
sem_b.sem_op = 1;
if(semop(semid,&sem_b,1)==-1)
{
printf("error\n");
exit(EXIT_FAILURE);
}
}
else break;
}
}
printf("send completed\n");
fclose(stream);
shmdt(sharem);
return 0;
}
以上是sender进程。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <string.h>
int main(int argc, char *argv[])
{
int running = 1;
char *shm_p = NULL;
int shmid;
int value;
int semid;
FILE *stream;
struct sembuf sem_b;
sem_b.sem_num=0;
sem_b.sem_flg=SEM_UNDO;
semid=semget((key_t)123456,1,0666|IPC_CREAT);
shmid = shmget((key_t)654321,(size_t)30,0600|IPC_CREAT);
shm_p = shmat(shmid,NULL,0);
printf("read data operate\n");
//stream = fopen("data.out","w+");
char buffer[50];
while(running)
{
while((value=semctl(semid,0,GETVAL))==1)
{
stream = fopen("data.out","a+");
sem_b.sem_op = -1;
if(semop(semid,&sem_b,1)==-1)
{
printf("error\n");
exit(EXIT_FAILURE);
}
strcpy(buffer,shm_p);
printf("%s\n",buffer);
//fwrite(shm_p,20,1,stream);
fprintf(stream,"%s\n",buffer);
fclose(stream);
}
if(strcmp(shm_p,"end")==0)
running--;
}
shmdt(shm_p);
if(shmctl(shmid,IPC_RMID,0)!=0)
{
perror("shmctl");
exit(EXIT_FAILURE);
}
if(semctl(semid,0,IPC_RMID,0)!=0)
{
perror("semctl");
exit(EXIT_FAILURE);
}
return 0;
}
以上是receiver进程。
sender:从data.in中读取数据写入到共享内存。
receiver:从共享内存读数据,写入到data.out。
以end作为结束符。
用信号量作为同步机制。
转载于:https://blog.51cto.com/yongjiuzhizhen/1323062