1、共享内存的通信方式
发送进程
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/shm.h>
int main()
{
int shmid; /*共享内存的内部标识*/
char *viraddr; /*定义附接到共享内存的虚拟地址*/
char buffer[BUFSIZ];
/*创建共享内存*/
shmid = shmget(1234, BUFSIZ, 0666|IPC_CREAT);
/*附接到进程的虚拟地址空间*/
viraddr = (char *)shmat(shmid, 0, 0);
/*循环输入信息,直到输入 end 结束*/
while(1)
{
puts("Enter some text:");
fgets(buffer, BUFSIZ, stdin);
strcat(viraddr, buffer); /*追加到共享内存*/
if(strncmp(buffer, "end", 3) ==0)
break;
}
shmdt(viraddr); /*断开链接*/
return 0;
}

图片.png
接收进程
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/shm.h>
int main()
{
int shmid;
char *viraddr;
/*获取共享内存*/
shmid = shmget(1234, BUFSIZ, 0666|IPC_CREAT);
/*附接到进程的虚拟地址空间*/
viraddr = (char *)shmat(shmid, 0, 0);
/*打印信息内容*/
printf("your message is :\n %s", viraddr);
/*断开链接*/
shmdt(viraddr);
/*撤销共享内存*/
shmctl(shmid, IPC_RMID, 0);
return 0;
}

图片.png
2、消息队列的通信方式
发送进程代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/msg.h>
#define MAXMSG 512 /*定义消息长度*/
/*定义消息缓冲区队列中的数据结构*/
struct my_msg
{
long int my_msg_type;
char some_text[MAXMSG];
}msg;
int main()
{
int msgid; /*定义消息缓冲区内部标识*/
char buffer[BUFSIZ]; /*用户缓冲区*/
/*创建消息队列*/
msgid = msgget(1234, 0666|IPC_CREAT);
/*循环向消息队列中发送消息,直到输入 end 结束*/
while(1)
{
puts("Enter some text:");
fgets(buffer, BUFSIZ, stdin);
msg.my_msg_type = 1;
strcpy(msg.some_text, buffer);
msgsnd(msgid, &msg, MAXMSG, 0); /*发送消息到缓冲队列中*/
if (strncmp(msg.some_text, "end", 3) == 0)
break;
}
return 0;
}

图片.png
接收进程代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/msg.h>
#define MAXMSG 512
struct my_msg
{
long int my_msg_type;
char some_text[MAXMSG];
}msg;
int main()
{
int msgid;
long int msg_to_receive = 0;
msgid = msgget(1234, 0666|IPC_CREAT);
/*循环从消息队列中接收消息,读入 end 结束接收*/
while (1)
{
msgrcv(msgid, &msg, BUFSIZ, msg_to_receive, 0);
printf("You wrote:%s", msg.some_text);
if (strncmp(msg.some_text, "end", 3) == 0)
break;
}
msgctl(msgid, IPC_RMID, 0);
return 0;
}

图片.png
3、管道通信
#include <stdio.h>
#include <unistd.h>
int main()
{
int p1, fd[2];
char outpipe[50]; /*定义读缓冲区*/
char inpipe[50] = "This is a message from child!"; /*定义写缓冲区*/
pipe(fd);
while ((p1 = fork()) == -1);
if (p1 == 0) /*子进程中写*/
{
write(fd[1], inpipe, 50);
}
else /*父进程中读*/
{
wait(0);
read(fd[0], outpipe, 50);
printf("%s \n", outpipe);
}
return 0;
}

图片.png