- 论坛徽章:
- 0
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define INITDAEMON {\
if(fork()>0) exit(0); \
setsid(); \
if(fork()>0) exit(0); \
}
#define SIZE (64*sizeof(char))
extern int errno;
int main(int argc , char *argv[])
{
//INITDAEMON;
int fd;
char* shmptr;
pid_t pid1;
int status;
struct sembuf P,V;
//union semun arg;
int mutxid;
if((fd = open("./t" , O_CREAT|O_TRUNC|O_RDWR , 00700)) < 0)
{
printf("%d %s\n" , __LINE__ ,strerror(errno));
return -1;
}
if(lseek(fd , SIZE , SEEK_SET) < 0)
{
printf("%d %s\n" , __LINE__ ,strerror(errno));
return -1;
}
write(fd , "" , 1);
if((shmptr =(char *) mmap(NULL , SIZE ,PROT_WRITE|PROT_READ|PROT_EXEC \
, MAP_SHARED , fd , 0)) == (void *)-1)
{
printf("%d %s\n" , __LINE__ , strerror(errno));
return -1;
}
memcpy(shmptr , "hellow world!" , sizeof("hello world!"));
if((mutxid = semget(IPC_PRIVATE , 1 , IPC_CREAT|00666)) == -1 )
{
printf("%d %s\n" , __LINE__ , strerror(errno));
return -1;
}
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;
if(semctl(mutxid , 0 ,SETVAL , 1) == -1) //初始化信号灯
perror("setctl setval error");
if((pid1 = fork()) < 0)
{
printf("%d %s\n" , __LINE__ , strerror(errno));
return -1;
}
else if(pid1 == 0)
{
printf("child pid is %d:\n",getpid());
printf("child from shm :\t %s\n", shmptr);
semop(mutxid , &P ,1 );
memset(shmptr , 0 , SIZE);
memcpy(shmptr , "hellow zjx!" , SIZE);
semop(mutxid , &V , 1);
exit(0);
}
else
{
printf("father pid is: %d\n",getpid());
//semop(mutxid , &P ,1 );
//memset(shmptr , 0 , sizeof(shmptr));
//memcpy(shmptr , "hellow Tian!" , sizeof("hello Tian!"));
//semop(mutxid , &V , 1);
waitpid(pid1 , &status);
semop(mutxid , &P ,1 );
memset(shmptr , 0 , sizeof(shmptr));
memcpy(shmptr , "hellow Tian!" , sizeof("hello Tian!"));
semop(mutxid , &V , 1);
printf("father from shm: \t %s\n", shmptr);
munmap(shmptr, SIZE);
semctl(mutxid,0,IPC_RMID);
return 0;
}
}
根据操作系统原理操作系统的信号灯是有限的,但是程序退出后用ipcs还是能查到,怎么没有自动释放?头次搞IPC请教前辈
RH linux 9 gcc3.2.2 |
|