红联Linux门户
Linux帮助

SETVAL 信号量问题?

发布时间:2009-06-17 04:55:21来源:红联作者:longwuyi
main()
{
int flag1,flag2,key,i,init_ok,tmperrno;
struct semid_ds sem_info;
struct seminfo sem_info2;
union semun arg; //union semun: 请参考附录2
struct sembuf askfor_res, free_res;
flag1=IPC_CREAT|IPC_EXCL|00666;
flag2=IPC_CREAT|00666;
key=ftok(SEM_PATH,'a');
//error handling for ftok here;
init_ok=0;
semid=semget(key,1,flag1); //create a semaphore set that only includes one semphore.
if(semid<0)
{
tmperrno=errno;
perror("semget");
if(tmperrno==EEXIST)
//errno is undefined after a successful
//library call( including perror call)
//so it is saved
//in tmperrno.
{
semid=semget(key,1,flag2);
//flag2 只包含了IPC_CREAT标志, 参数nsems(
//这里为1)必须与原来的信号灯数目一致
arg.buf=&sem_info;
for(i=0; i {
if(semctl(semid, 0, IPC_STAT, arg)==-1)
{
perror("semctl error");
i=max_tries;
}
else
{ //sem_otime非0,表示初始化完毕
if(arg.buf->sem_otime!=0)
{
i=max_tries;
init_ok=1;
}
else
sleep(1);
}
}
if(!init_ok)
// do some initializing, here we assume that the first process that creates the sem will
// finish initialize the sem and run semop in max_tries*1 seconds. else it will not run
// semop any more.
{
arg.val=1;
if(semctl(semid,0,SETVAL,arg)==-1) perror("semctl setval error"); }
}
代码中的红色部分设置其它进程创建的信号量为互斥型.
是否能这样做, 若创建该信号量的进程将其设置为计数型信号量, 则该代码会产生何种效果?
文章评论

共有 1 条评论

  1. jiehe 于 2009-06-17 09:56:06发表:

    看不懂哦。