本文主要是介绍共享内存、网络通信,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、共享内存(同一主机间通信)
(1) 产生key值
key_t ftok(const char *pathname, int proj_id);
On success, the generated key_t value is returned. On failure -1 is returned, with errno indicating the error as for the stat(2) system call.
(2)申请对象
int shmget(key_t key, size_t size, int shmflg);
On success, a valid shared memory identifier is returned. On error, -1 is returned, and errno is set to indicate the error.
(3)绑定
void *shmat(int shmid, const void *shmaddr, int shmflg);
On success, shmat() returns the address of the attached shared memory segment; on error, (void *) -1 is returned, and errno is set to indicate the cause of the error.
(4) 解除绑定
int shmdt(const void *shmaddr);
On success, shmdt() returns 0; on error -1 is returned, and errno is set to indicate the cause of the error.
(5)销毁
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>void hander(int signo)
{}
int main(int argc, char *argv[])
{key_t key = ftok("/",'b');if(key == -1){perror("ftok");return 1;}//printf("key = %d\n",key);int shmid = shmget(key,1024,IPC_CREAT|0666);if(shmid == -1){perror("shmget");return 1;}//printf("id = %d\n",shmid);void *p = shmat(shmid,NULL,0);if((void *)-1 == p){perror("shmat");return 1;}signal(SIGUSR1,hander);pid_t *q = (pid_t *)p;*q = getpid();char *s = (char *)p;while(1){printf("%s\n",s);pause();if(strcmp(s,"quit") == 0)break;} if(shmdt(p) == -1){perror("shmdt");return 1;}if(shmctl(shmid,IPC_RMID,NULL) == -1){perror("shmctl");return 1;}return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>int main(int argc, char *argv[])
{key_t key = ftok("/",'b');if(key == -1){perror("ftok");return 1;}//printf("key = %d\n",key);int shmid = shmget(key,1024,IPC_CREAT|0666);if(shmid == -1){perror("shmget");return 1;}//printf("id = %d\n",shmid);void *p = shmat(shmid,NULL,0);if((void *)-1 == p){perror("shmat");return 1;}pid_t *q = (pid_t *)p;printf("open pid = %d\n",*q);pid_t pid = *q;while(1){char *s = (char *)p;fgets(s,1024,stdin);s[strlen(s) - 1] = '\0';kill(pid,SIGUSR1);if(strcmp(s,"quit") == 0)break;}if(shmdt(p) == -1){perror("shmdt");return 1;}if(shmctl(shmid,IPC_RMID,NULL) == -1){perror("shmctl");return 1;}return 0;
}
2、网络间通信
int socket(int domain, int type, int protocol);
osi 7 层参考模型
1. 物理层
规定了物理层面的电气特性及相关机械特性
物理层面数据的传输 --- 一位一位二进制数据 //比特流
2. 数据链路层
规定了 传输数据的格式 //帧数据
//控制传输过程可靠
3. 网络层 (网际层)
用于解决 网络 与 网络之间 数据传输 //数据包
4. 传输层
传输控制层,控制传输过程,保证数据完整和可靠
5. 会话层
处理一次会话过程
6. 表示层
规定了 传输数据的格式 和 方式 //加密
7. 应用层
就是直接获取要收发的数据
tcp/ip 五层模型
应用层
传输层
网络层
数据链路层
物理层
4层模型
应用层
传输层
网络层
网络接口层
这篇关于共享内存、网络通信的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!