- 论坛徽章:
- 0
|
多进程通信下的共享内存应用问题想向大家请教!
部分代码如下:
*************************
nt main (int argc,char ** argv)
{
.......................
act_SIGUSR1.sa_handler=&SIGUSR1_hand;
sigemptyset(&act_SIGUSR1.sa_mask);
act_SIGUSR1.sa_flags=0;
sigaction(SIGUSR1,&act_SIGUSR1,NULL);
act_SIGUSR2.sa_handler=&SIGUSR2_hand;
sigemptyset(&act_SIGUSR2.sa_mask);
act_SIGUSR2.sa_flags=0;
sigaction(SIGUSR2,&act_SIGUSR2,NULL);
............................
result=INIT_Daemon();
result=CREATE_Daemon();
.............................
}
int INIT_Daemon(void)
{
//store the parent ID
pid_parent=getpid();
//initialize the IPC sem
if((semid=semget(IPC_PRIVATE,2,777|IPC_CREAT))==-1)
{
.......................................
}
init_semaphore_struct(&sem0wait,0,-1,SEM_UNDO);
init_semaphore_struct(&sem0signal,0,1,SEM_UNDO);
init_semaphore_struct(&sem1wait,1,-1,SEM_UNDO);
init_semaphore_struct(&sem1signal,1,1,SEM_UNDO);
if((semop(semid,&sem0signal,1)||semop(semid,&sem1signal,1))==-1)
{
........................................
}
//initialize the IPC share memory
if ((shmid=shmget(IPC_PRIVATE,MEMSIZE+4,777|IPC_CREAT))==-1)
{
.....................................
}
............................................
}
int CREATE_Daemon(void)
{
........................
usleep(500000);
setsid();
chdir ("/");
umask(0);
for (i=0;i<3;++i)
{
close(i);
}
if((int)(memory_header=shmat(shmid,0,0))==-1)
{
kill(pid_parent,SIGUSR2);
exit(1);
}
................................
//register the signal handle function
struct sigaction act_SIGUSR1;
act_SIGUSR1.sa_handler=&m_handle;
sigemptyset(&act_SIGUSR1.sa_mask);
act_SIGUSR1.sa_flags=0;
sigaction(SIGUSR1,&act_SIGUSR1,NULL);
while(1)
{
while((semflag=semop(semid,&sem0wait,1))==-1&&errno==EINTR);//wait the sem
.................................
while((semflag=semop(semid,&sem0signal,1))==-1&&errno==EINTR);//release the sem
.................................
}
}
******************************************************
上面便是,我看的代码的主要部分。它是通过 CREATE_Daemon()函数创建一个精灵进程,而父进程仍然往后执行。
让我困惑的就是,在CREATE_Daemon函数中,它又重新声明了act_SIGUSR1信号,而且名字和main函数中相同,只是信号处理函数不一样。如果fork后,子程序会重新从main函数开始运行,在main中,act_SIGUSR1信号会被声明,而,act_SIGUSR1信号在CREATE_Daemon函数中也会同样声明,合理吗?(这样不是有两次声明了!)在此,我想到另外一个问题,这两个进程如何能进行共享内存的实现(当然它们是靠信号灯同步的),因为子进程从main函数处,又会重新申请新的共享内存,而且信号灯也是在两个进程都声明了,这样不就是两个变量了,这能实现ipc吗?
可能我对fork还不是很熟悉,希望大家指点! |
|