⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 msgqueue.c

📁 linux下串口的访问
💻 C
字号:
#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/msg.h> 

#include "msgqueue.h"
#include "wcommon.h"
#include "syslog.h"

int MsgIdGet( int key )
{
	int id;

	//id  = msgget(key,0);
	id = msgget( key, IPC_CREAT|0666 );
	if ( id < 0 )
	{
		printf( "id=%d\n", id );
		perror("msgget error.");
		return -1;
	}
	return id;
}

int MsgRecv( int id, unsigned char * buf, int type )
{
	int len;
	struct { 
		long msg_type; 
		char msg_data[MsgDataLen]; 
         } rMsg; 

	if ( buf==0 )
	{
		Print("MsgRecv: para error.");
		return -1;
	}
	type = type <0 ? -type : type;	// type must more than 0
	len = msgrcv(id, (char *)(&rMsg), MsgDataLen, type, 0 ); 
	if ( len<0 || len>MsgDataLen )
	{
		Perror("msgrcv error.");
                Print( "msgrcv error." );
		return -1;
	}
	memcpy( buf, rMsg.msg_data, len );
	return len;
} 

int MsgSend( int id, unsigned char * buf, int buflen, int type )
{
	int ret;
	struct { 
		long msg_type; 
		char msg_data[MsgDataLen]; 
         } rMsg; 
	
	if ( buf==0 || buflen<0 )
	{
		printf("para error.\n");
		return -1;
	}

	memcpy( rMsg.msg_data, buf, buflen );
	type = type <0 ? -type : type;	// type must more than 0
	rMsg.msg_type = type;
	ret = msgsnd(id, (char *)&rMsg, buflen, 0 ); 
	if ( ret<0 )
	{
		perror("msgsnd error.");
		return -2;
	}
	return ret;	
} 

int MsgDele( int id )
{
	if( msgctl(id,IPC_RMID,(struct msqid_ds*)0)<0 ) 
	{
		perror("can't PMIN message queue 1.\n"); 
		return -1;
	}
	return 0;
}

/*
int main(int argc, char *argv[])
{
// 	if ( argc < 2 )
// 	{
// 		printf("para too less\n");
// 		return -1;
// 	}

	int id = MsgIdGet( 123321 );
	char buf[32];

	printf("id=%d\n",id);
	if ( id==-1 )
		return -1;

	int fid;

	fid = fork();
	if ( fid==0 )
	{
		printf("Send hello...\n");
		printf( "ret=%d\n", MsgSend( id, "hello", 6, 1 ) );
		printf("Send end\n");
		exit(0);
	}

	printf("Recv ...\n");
	printf( "ret=%d\n", MsgRecv( id, buf, 1 ) );
	printf("Buf:%s\n", buf);
	

// 	if ( argv[1][0]=='s' )
// 	{
// 		printf("Send hello...\n");
// 		printf( "ret=%d\n", MsgSend( id, "hello", 6, 1 ) );
// 		printf("Send end\n");
// 	}
// 	else
// 	{
// 		printf("Recv ...\n");
// 		printf( "ret=%d\n", MsgRecv( id, buf, 1 ) );
// 		printf("Buf:%s\n", buf);
// 	}
	//MsgDele(id);
	return 0;
}
//*/

// /opt/brcm/hndtools-mipsel-uclibc-3.2.3/bin/mipsel-uclibc-gcc -c msgqueue.c -o msg

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -