2、使用系统调用SHMGET(),SHMAT()编制一长度为1K的消息发送和接收的程序。 要求: (1)main函数建立一个KEY 为75 的共享区,并将第一个字节置为0。作为数据空的标志等待其他进程发来的消息。收到数据后显示“ Main recieved help ”。 (3)创建一个进程P1,P1建立一个KEY为75的共享区,当共享取得第一个字节为0时,main空闲,可发送请求:P1填入“HELP”,发送数据后显示“P1 send help”。
时间: 2024-02-24 08:00:39 浏览: 27
以下是实现要求的C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
#define SHM_KEY 75
int main() {
char *shm;
int shmid;
int flag = 0;
// 创建共享内存
shmid = shmget(SHM_KEY, SHM_SIZE, IPC_CREAT | 0666);
if (shmid < 0) {
printf("Failed to create shared memory!\n");
exit(1);
}
// 将共享内存附加到当前进程
shm = shmat(shmid, NULL, 0);
if (shm == (char *) -1) {
printf("Failed to attach shared memory to process!\n");
exit(1);
}
// 等待其他进程发送消息
while (1) {
if (shm[0] == 0) {
printf("Main is waiting for message...\n");
flag = 1;
} else if (flag == 1 && strcmp(shm + 1, "HELP") == 0) {
printf("Main received help!\n");
shm[0] = 0;
}
sleep(1);
}
// 分离共享内存
shmdt(shm);
return 0;
}
```
程序中,通过调用 `shmget()` 系统调用创建一个长度为1K的共享内存,并将第一个字节置为0。主进程等待其他进程发送消息,当共享内存的第一个字节为0时,表示主进程空闲,其他进程可以向共享内存写入消息。当主进程接收到其他进程发送的消息后,输出提示信息并将共享内存的第一个字节重新置为0。
下面是进程P1的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
#define SHM_KEY 75
int main() {
char *shm;
int shmid;
// 创建共享内存
shmid = shmget(SHM_KEY, SHM_SIZE, IPC_CREAT | 0666);
if (shmid < 0) {
printf("Failed to create shared memory!\n");
exit(1);
}
// 将共享内存附加到当前进程
shm = shmat(shmid, NULL, 0);
if (shm == (char *) -1) {
printf("Failed to attach shared memory to process!\n");
exit(1);
}
// 等待主进程空闲
while (1) {
if (shm[0] == 0) {
printf("P1 is sending help...\n");
strcpy(shm + 1, "HELP");
shm[0] = 1;
break;
}
sleep(1);
}
// 分离共享内存
shmdt(shm);
return 0;
}
```
程序中,通过调用 `shmget()` 系统调用创建一个长度为1K的共享内存,并将第一个字节置为0。进程P1等待主进程空闲,当共享内存的第一个字节为0时,表示主进程空闲,进程P1向共享内存写入消息“HELP”。然后将共享内存的第一个字节置为1,表示有消息发送。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)