阅读背景:

Linux下C语言实现显示SYSTEM V信号量信息的小工具

来源:互联网 

1、源代码

/*************************************************************************
  > File Name: svsem_myls.c
  > Author:zhangshengshan
  > Mail: [email protected] 
  > show all the semophmore
 ************************************************************************/
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<sys/sem.h>
#include "semun.h"
#include <sys/ipc.h>
int get_sem_index(int *pIndex,union semun *pSemun)
{
	*pIndex = semctl(0,0,SEM_INFO,*pSemun);

	if (-1==*pIndex)
	{
		return -1;
	}
	return *pIndex;
}
int main(int argc,char * argv[]){

	union semun union_sem;
	union semun arg;
	union semun dummy;
	struct semid_ds ds_sem;
	struct seminfo info_sem;
	int index=-1;
	int id_sem=0;
	int num_sem=0;
	int i=-1;
	int j=-1;
	int k=-1;

	union_sem.__buf=&info_sem;
	//arg.buf=&ds_sem;
	//从内核获取信号量的索引  
	if( -1==get_sem_index(&index,&union_sem))
	{
		printf("get index failure!\n");
		exit(1);
	}
	//show_semid();
	printf("semid  num  sem# value SEMPID SEMNCNT SEMZCNT\n");
	for (i=0;i<=index;i++)
	{
		arg.buf=&ds_sem;
		//获取信号集描述符
		id_sem=semctl(i,0,SEM_STAT,arg);
		k=arg.buf->sem_nsems;
		//show  every sem info in id_sem
		//member array is a pointor!
		arg.array=calloc(arg.buf->sem_nsems,sizeof(arg.array[0]));
		if (arg.array == NULL)
		{
			printf("calloc error!\n");
			exit (9);
		}
		// here the param will be changed! because it is a union!
		if (semctl(id_sem,0,GETALL,arg)==-1)
		{
			printf("semctl-getALL\n");
			exit(8);
		}
		printf("now arg.buf->sem_nsems is %d, and ds_sem.sem_nsems is %d\n",arg.buf->sem_nsems,ds_sem.sem_nsems);	
		//printf("sem # value  SEMPID SEMNCNT SEMZCNT\n");
		for(j=0;/**/ j<k;j++)
		{
			printf("%5d %5d %3d %5d %5d %5d %5d\n",id_sem,k,j,arg.array[j],\
					semctl(id_sem,j,GETPID,dummy),\
					semctl(id_sem,j,GETNCNT,dummy),\
					semctl(id_sem,j,GETZCNT,dummy));
		}
	}
	return 0;
}/**************************************



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: