日期:2014-05-16  浏览次数:20800 次

不显示删除回复显示所有回复显示星级回复显示得分回复 父子进程间通信:1:共享内存2:信号量:父进程里请求信号量错误,高手帮忙
linux 环境下gcc

单步调试发现main函数里的ID和write函数里的ID 值不一样。
不知道问题出现在哪里。。请帮忙看下。

[code=C/C++]
[
/*父子进程间通信:1>共享内存2>信号量*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdarg.h>
#include <sys/sem.h>
#include <errno.h>

union semun//声明联合体供semctl使用
  {
  int val;//存放命令字SETVAL的值
  struct semid_ds *buf;//存放IPC_STAT或从信号量里取的的值
  unsigned short *array;
  struct seminfo *_but;
  };

#define SIZE 100
   
void request_sem(int id ); 
void release_sem(); 
void sem_delete();
void write_shm(int shmid, char *segptr, char *strin);  
void read_shm(int shmid, char *segptr, char *strout); 
void remove_shm(int shmid);
   
int semheld = 0;
int id = 0;
pid_t pid;

int ret;

int main(int argc, char *argv[])
{
int shmid;
char *segptr ;
union semun my_union;
char strin[100];
char strout[100];
id = semget(IPC_PRIVATE, 1, SHM_R|SHM_W);//创建信号量
if (id != -1)
{
atexit(&sem_delete);
my_union.val = 1;//初始化信号量
if (semctl(id, 0, SETVAL, my_union) == -1)
{
printf("semctl failed \n");
exit(-1);
}
}
else 
printf("xinhaoliangchuangjianshibai");
if((shmid = shmget(IPC_PRIVATE, SIZE, IPC_CREAT|0600)) == -1)//创建共享内存
{
perror("shmget");
exit(1);

}
if((segptr = (char *)shmat(shmid, NULL, 0)) == (void *)-1)//连接共享内存
printf("segptr error\n");
pid = fork();
if (pid == 0)//子进程负责往共享内存写数据
{

printf("In child process:\n");

request_sem(id);
printf("Please input some char\n");
scanf("%s", strin);
setbuf(stdin, NULL);
write_shm(shmid, segptr, strin);
release_sem(id);
exit(0);
}
if (pid != -1)//父进程负责往共享内存里读
{
sleep(5);
pid = wait(&ret);

printf("In child process:\n");
request_sem(id);
read_shm(shmid, segptr, strout);
printf("Read data from share memory is: %s", strout);
release_sem(id);
}
 
  remove_shm(shmid);
  sem_delete();

}  
   
   
   
/*请求信号量*/
void request_sem(int id )
{
struct sembuf sb;
if (semheld >0)
{
printf("I have hold a semaphor\n");
return ;
}
sb.sem_num = 0;
sb.sem_op = -1;
sb.sem_flg = SEM_UNDO;
printf("Requesting semaphor\n");
setbuf(stdout, NULL);

if (semop(id, &sb, 1) == -1)
{
printf("semop error:%s", strerror(errno));
exit(-1);
}
semheld++;
printf("current process have hold this semaphor!\n");
}
/* 释放信号量*/
void release_sem(int id)
{
struct sembuf sb;
if (semheld <1)
{
printf("I don't have any semaphor\n");
return ;
}
sb.sem_num = 0;
sb.sem_op = 1;
sb.sem_flg = SEM_UNDO;
if (semop(id, &sb, 1) == -1)
{
printf("Semaphor release failed \n");
exit(-1);
}
semheld--;
printf("Sem release successfully\n");
}
/*删除信号量*/

void sem_delete()
{
if (semctl(id, IPC_RMID, 0) == -1)<