两个程序之间的通信c代码
时间: 2024-01-03 10:04:35 浏览: 31
程序之间的通信可以通过进程间通信(IPC)来实现。下面是两个程序之间通过共享内存进行通信的C代码示例:
程序1:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main()
{
int shmid;
char *shmaddr;
key_t key = ftok(".", 'a'); // 生成一个key
// 创建共享内存
shmid = shmget(key, SHM_SIZE, IPC_CREAT|0666);
if (shmid == -1) {
perror("shmget error");
exit(EXIT_FAILURE);
}
// 连接共享内存
shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (void *)-1) {
perror("shmat error");
exit(EXIT_FAILURE);
}
// 写入共享内存
strcpy(shmaddr, "Hello, world!");
// 断开共享内存连接
if (shmdt(shmaddr) == -1) {
perror("shmdt error");
exit(EXIT_FAILURE);
}
return 0;
}
```
程序2:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main()
{
int shmid;
char *shmaddr;
key_t key = ftok(".", 'a'); // 使用同样的key
// 获取共享内存
shmid = shmget(key, SHM_SIZE, 0666);
if (shmid == -1) {
perror("shmget error");
exit(EXIT_FAILURE);
}
// 连接共享内存
shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (void *)-1) {
perror("shmat error");
exit(EXIT_FAILURE);
}
// 读取共享内存
printf("%s\n", shmaddr);
// 断开共享内存连接
if (shmdt(shmaddr) == -1) {
perror("shmdt error");
exit(EXIT_FAILURE);
}
// 删除共享内存
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl error");
exit(EXIT_FAILURE);
}
return 0;
}
```
这两个程序通过共享内存进行通信,程序1将字符串“Hello, world!”写入共享内存,程序2读取共享内存中的数据并输出。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)