一个不理解的程序段??
int main()
{
int shmid;
char *shmaddr;
struct shmid_ds buf;
shmid = shmget(KEY, SIZE, IPC_CREAT | 0600);
if(shmid == -1) {
printf( "create share memory failed: %s\n ",strerror(errno));
return 0;
}
printf( "before if...else... \n ");
if(fork() == 0) {
————————
shmaddr = (char *)shmat(shmid, NULL, 0);
if(shmaddr == (void *)-1) {
printf( "connect to the share memory failed: %s\n ", strerror(errno));
return 0;
}
strcpy(shmaddr, "hello, this is a child process! ");
shmdt(shmaddr);
return 0;
—————
}
else {
————
sleep(3);
shmctl(shmid, IPC_STAT, &buf);
printf( "size of the share memory: shm_segsz = %d bytes \n ",
buf.shm_segsz);
printf( "process id of creater: shm_cpid = %d \n ", buf.shm_cpid);
printf( "process id of the last operator: shm_lpid = %d \n ",
buf.shm_lpid);
shmaddr = (char *)shmat(shmid, NULL, 0);
if(shmaddr == (void *)-1) {
printf( "connect the share memory failed: %s \n ", strerror(errno));
return 0;
}
printf( "print the content of the share memory: %s \n ", shmaddr);
shmdt(shmaddr);
shmctl(shmid, IPC_RMID, NULL);
}
}
这段程序是《linux边干边学》中的一个例子,
上面有下划线的部分,是个if语句,在fork子进程中,最后使用了return 0 语句,但
是,好像也没有退出main函数, 接着执行了else部分的语句;好像没有这个
if...else...一样,不知道为什么?
------解决方案--------------------是父进程执行的吧,吧进程号打印出来就知道了!
------解决方案--------------------从fork开始,程序一份为二。
也就是说,fork后有2个程序在同时执行。一个程序进入了if{},另一个程序进入了else{}