|
楼主 |
发表于 2011-6-20 16:31
|
显示全部楼层
虛擬機沒裝共享。。。。
繼續試試。。。。
#define BUFSIZ 512
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<linux/shm.h>
#include<linux/sem.h>
int empty;
int full;
main(){
int myshm;
char *viraddr;
char buffer[BUFSIZ];
struct sembuf P,V;
union semun arg;
empty=semget(1366,1,IPC_CREAT|0666);
full=semget(1155,1,IPC_CREAT|0666);
myshm=shmget(775,BUFSIZ,0666|IPC_CREAT); //
viraddr=(char*)shmat(myshm,0,0);
arg.val=1;
if(semctl(empty,0,SETVAL,arg)==-1)
perror("semctl setval error");
arg.val=0;
if(semctl(full,0,SETVAL,arg)==-1)
perror("semctl setval error");
P.sem_num = 0;
P.sem_op =-1;
P.sem_flg = SEM_UNDO;
V.sem_num = 0;
V.sem_op = 1;
V.sem_flg = SEM_UNDO;
while(1){
semop(empty,&P,1);
puts("Put some text:");
fgets(buffer,BUFSIZ,stdin);
strcat(viraddr,buffer);
semop(full,&V,1);
if(strncmp(buffer,"end",3)==0)
break;
}
shmdt(viraddr);
exit(0);
}
Mysem.c
#define BUFSIZ 512
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<linux/shm.h>
#include<linux/sem.h>
int empty;
int full;
main(){
int myshm,P1;
char *viraddr;
char buffer[BUFSIZ];
struct sembuf P,V;
union semun arg;
empty=semget(1366,1,IPC_CREAT|0666);
full=semget(1155,1,IPC_CREAT|0666);
myshm=shmget(775,BUFSIZ,0666|IPC_CREAT);//
viraddr=(char*)shmat(myshm,0,0);
arg.val=1;
if(semctl(empty,0,SETVAL,arg)==-1)
perror("semctl setval error");
arg.val=0;
if(semctl(full,0,SETVAL,arg)==-1)
perror("semctl setval error");
P.sem_num = 0;
P.sem_op =-1;
P.sem_flg = SEM_UNDO;
V.sem_num = 0;
V.sem_op = 1;
V.sem_flg = SEM_UNDO;
while((P1=fork())== -1);
if(P1 == 0){
execl("./myinput",0,NULL);
}
else{
while(1){
semop(full,&P,1);
printf("Your message is :\n%s",viraddr);
semop(empty,&V,1);
if(strstr(viraddr,"end"))
break;
}
}
wait(0);
shmdt(viraddr);
shmctl(myshm,IPC_RMID,0);
semctl(empty,IPC_RMID,0);
semctl(full,IPC_RMID,0);
printf("Parent exit!\n");
exit(0); |
|
关于我们