linux先进程通信 管道方式和消息队列

#include<iostream>
#include<cstdio>
#include<unistd.h>
#include<sys/types.h>
typedef long long ll;
#define eps 1e-8

using namespace std;

int main()
{
    int i,pid;
    pid=fork();
	if(pid<0)
	{
		printf("error\n");
	}
    else if(pid==0)
	{
		for(i=1;i<=3;i++)
		   printf("this is child process\n");
	}
	else 
	{
		for(i=1;i<=3;i++)
			printf("this is father process\n");
	}
   return 0;
}






#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<unistd.h>
#include<error.h>
using namespace std;

int main()
{
	static const char mesg[]="Happy new year";
	char buf[BUFSIZ];
	int rcount,wcount;
	int p_fd[2];
	int n;

	if(pipe(p_fd)<0)
	{
		printf("pipe error\n");
		exit(EXIT_FAILURE);
	}
	printf("Read end = fd %d Write end = fd %d\n",p_fd[0],p_fd[1]);
    n=strlen(mesg);
	if((wcount=write(p_fd[1],mesg,n))!=n)
	{
		printf("write error\n");
		exit(EXIT_FAILURE);
	}
	if((rcount=read(p_fd[0],buf,BUFSIZ))!=n)
	{
		printf("write error\n");
		exit(EXIT_FAILURE);
	}
	buf[rcount]='\0';
    printf("Read<%s> from pipe.\n",buf);
	return 0;
}



#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<error.h>
#include<sys/msg.h>
using namespace std;

struct msg{
    long type;
	char text[BUFSIZ];
};

int main()
{
   int i,j,qid;
   struct msg p_msg_r,p_msg_w;
   int key;
   key=IPC_PRIVATE;
   if((qid=msgget(key,IPC_CREAT|0666))<0)
   {
	   printf("error\n");
	   exit(EXIT_FAILURE);
   }
   printf("please input the information:\n");
   if(fgets(p_msg_w.text,BUFSIZ,stdin)==NULL)
   {
	   printf("wrong,no passage send\n");
	   exit(EXIT_FAILURE);
   }
   p_msg_w.type=10;
   int len1=strlen(p_msg_w.text);
   if(msgsnd(qid,&p_msg_w,len1,IPC_NOWAIT)<0)
   {
	   printf("error in sending message\n");
	   perror("msgerror");
	   exit(EXIT_FAILURE);
   }
   printf("information has been sent\n");
   int len2=msgrcv(qid,&p_msg_r,BUFSIZ,10,IPC_NOWAIT|MSG_NOERROR);
   if(len2>0)
   {
	   p_msg_r.text[len2]='\0';
	   printf("reading queue id  =%d\n",qid);
	   printf("message      type =%ld\n",p_msg_r.type);
	   printf("message       len =%d\n",len2);
	   printf("message      text =%s\n",p_msg_r.text);
	   exit(EXIT_SUCCESS);
   }
   else
   {
	   perror("msgrcv");
	   exit(EXIT_FAILURE);
   }
   return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值