2月5日作业

通过消息队列实现进程之间通信代码示例

send.c

#include 
struct msgbuf
{
	long mtype;
	char mtext[1024];
};
#define MSGSIZE (sizeof(struct msgbuf)-sizeof(long))
int main(int argc, const char *argv[])
{
	key_t key = ftok("/",'k');
	if(key == -1)
	{
		perror("ftok error");
		return -1;
	}
	int msqid = msgget(key,IPC_CREAT|0664);
	if(msqid == -1)
	{
		perror("msgget error");
		return -1;
	}
	struct msgbuf buf = {.mtype=100};
	while(1)
	{
		bzero(buf.mtext,sizeof(buf.mtext));
		fgets(buf.mtext,sizeof(buf.mtext),stdin);
		buf.mtext[strlen(buf.mtext)-1] = '\0';
		if(msgsnd(msqid,&buf,MSGSIZE,0) != 0)
		{
			perror("msgsnd error");
			return -1;
		}
		if(strcmp(buf.mtext,"quit") == 0)
		{
			break;
		}
	}
	return 0;
}

recv.c

#include 
struct msgbuf
{
	long mtype;
	char mtext[1024];
};
#define MSGSIZE (sizeof(struct msgbuf)-sizeof(long))
int main(int argc, const char *argv[])
{
	key_t key = ftok("/",'k');
	if(key == -1)
	{
		perror("ftok error");
		return -1;
	}
	int msqid;
	if((msqid = msgget(key,IPC_CREAT|0664)) == -1)
	{
		perror("msgget error");
		return -1;
	}
	struct msgbuf buf;
	while(1)
	{
		bzero(buf.mtext,sizeof(buf.mtext));
		if(msgrcv(msqid,&buf,MSGSIZE,0,0) == -1)
		{
			perror("msgrcv error");
			return -1;
		}
		printf("message is :%s\n",buf.mtext);
		if(strcmp(buf.mtext,"quit") == 0)
		{
			break;
		}
	}
	if(msgctl(msqid,IPC_RMID,NULL) == -1)
	{
		perror("msgctl error");
		return -1;
	}
	return 0;
}

效果演示

2月5日作业_第1张图片

你可能感兴趣的:(前端,服务器)