server.c

来自「源码包中是我在学习Linux进程间通信时所写的关于五种通信方式(管道」· C语言 代码 · 共 60 行

C
60
字号
/* server */#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#include <string.h>#define	KEY_MSG		0x101#define	MSGSIZE		128int main(){	int	msgid;	struct	msgbuf	{		long	mtype;		int	subtype;		char 	mtext[MSGSIZE];	}buf;		/* create a message queue */	msgid = msgget( KEY_MSG, IPC_CREAT|0666 );	/* unlimit loop, when meet a exit flag, break */	while( 1 )	{		msgrcv( msgid, &buf, MSGSIZE+4, 1L, 0 );			/* receive message from client1 */		printf( "Receive client message: %s\n", buf.mtext );				if( buf.mtext[0] == 'x' || buf.mtext[0] == 'X' )                {                        strcpy( buf.mtext, "x" );                        buf.mtype = 2L;                        msgsnd( msgid, &buf, MSGSIZE+4, 0 );             /* send quit message to client1 */                        buf.mtype = 3L;                        msgsnd( msgid, &buf, MSGSIZE+4, 0 );             /* send quit message to client2 */                        break;                }				if( buf.subtype == 2 )		{			buf.mtype = 3L;			msgsnd( msgid, &buf, MSGSIZE+4, 0);		}			else		{			buf.mtype = 2L;                        msgsnd( msgid, &buf, MSGSIZE+4, 0);		}	}		sleep(5);		/* if quit, wait first, make sure that both client quit */	msgctl( msgid, IPC_RMID, NULL );		exit(0);	}

⌨️ 快捷键说明

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