1.通过信号灯集实现两个文件的交流
#include <myhead.h>
#include"sem.h"
int main(int argc, const char *argv[])
{
int semid=init_sem(4);
pid_t pid=1;
pid=fork();
key_t key=ftok("/",'t');
if(key==-1)
{
perror("ftok error");
return -1;
}
int shmid;
if((shmid=shmget(key,4096,IPC_CREAT|0664))==-1)
{
perror("shmget error");
return -1;
}
char *addr=NULL;
if((addr=shmat(shmid,NULL,0))==(void *)-1)
{
perror("shmat error");
return -1;
}
if(pid<0)
{
perror("fork error");
return -1;
}
else if(pid==0)
{
while(1)
{
P(semid,3);
printf("读取为:%s\n",addr);
V(semid,2);
if(strcmp(addr,"quit")==0)
{
break;
}
}
}
else{
while(1)
{
P(semid,0);
fgets(addr,4096,stdin);
addr[strlen(addr)-1]='\0';
V(semid,1);
if(strcmp(addr,"quit")==0)
{
break;
}
}
}
if(shmdt(addr)==-1)
{
perror("shmdt error");
return -1;
}
if(shmctl(shmid,IPC_RMID,NULL)==-1)
{
perror("shmctl error");
return -1;
}
del_sem(semid);
return 0;
}
#include <myhead.h>
#include"sem.h"
int main(int argc, const char *argv[])
{
int semid=init_sem(4);
pid_t pid=1;
pid=fork();
key_t key=ftok("/",'t');
if(key==-1)
{
perror("ftok error");
return -1;
}
int shmid;
if((shmid=shmget(key,4096,IPC_CREAT|0664))==-1)
{
perror("shmget error");
return -1;
}
char *addr=NULL;
if((addr=shmat(shmid,NULL,0))==(void *)-1)
{
perror("shmat error");
return -1;
}
if(pid<0)
{
perror("fork error");
return -1;
}
else if(pid>0)
{
while(1)
{
P(semid,1);
printf("读取为:%s\n",addr);
V(semid,0);
if(strcmp(addr,"quit")==0)
{
break;
}
}
}
else{
while(1)
{
V(semid,2);
P(semid,2);
fgets(addr,4096,stdin);
addr[strlen(addr)-1]='\0';
V(semid,3);
if(strcmp(addr,"quit")==0)
{
break;
}
}
}
if(shmdt(addr)==-1)
{
perror("shmdt error");
return -1;
}
if(shmctl(shmid,IPC_RMID,NULL)==-1)
{
perror("shmctl error");
return -1;
}
del_sem(semid);
return 0;
}
现象:
2.思维导图