cjozGV 的學生作業(yè):
#include
#include
#include
#include
#include
#define PATHNAME "." // 用于生成key的路徑
#define PRO_ID 100 // 用于生成key的ID
#define SZ 1024 // 每次傳輸緩沖區(qū)大小 1kb
typedef struct {
int data_size; // 當前寫入數(shù)據(jù)的長度
int finished; // 是否傳輸結束標志 1 表示結束
char buffer[SZ]; // 實際存放文件的緩沖區(qū)
} shm_block;
int main(){
// 1. 生成共享內(nèi)存的key 必須和寫進程一致
key_t key = ftok(PATHNAME,PRO_ID);
// 2. 獲取共享內(nèi)存
int shmid = shmget(key, sizeof(shm_block),IPC_CREAT | 0666);
// 3. 將共享內(nèi)存掛接到當前進程地址空間
shm_block *shm = (shm_block*)shmat(shmid,NULL,0);
// 4. 打開輸入文件,用于保存接收到的數(shù)據(jù)
FILE *fp = fopen("output.txt","wb");
if (!fp){
perror("fopen");
exit(1);
}
// 5. 循環(huán)從共享內(nèi)存讀取數(shù)據(jù)
while (1){
// 如果寫進程寫入數(shù)據(jù) (data_size > 0)
if (shm->data_size > 0) {
// 把數(shù)據(jù)寫入到文件
fwrite(shm->buffer,1,shm->data_size,fp);
// 標記數(shù)據(jù)已經(jīng)消費,通知寫進程可以繼續(xù)寫
shm->data_size = 0;
}
// 如果寫進程已經(jīng)結束 (finished=1 且 data_size = 0),退出循環(huán)
if (shm->finished && shm->data_size == 0) {
break;
}
// 避免cpu空轉,稍微休眠一下
usleep(1000);
}
// 6. 關閉文件
fclose(fp);
// 7. 將共享內(nèi)存從當前進程分離
shmdt(shm);
// 8. 刪除共享內(nèi)存(釋放系統(tǒng)資源)
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
#include
#include
#include
#include
#include
#include
#define PATHNAME "." // 用于生成key的路徑
#define PRO_ID 100 // 用于生成key的ID
#define SZ 1024 // 每次傳輸緩沖區(qū)的大小
typedef struct {
int data_size; // 當前寫入數(shù)據(jù)的長度
int finished; // 是否傳輸結束標志
char buffer[SZ]; // 實際存放文件的緩沖區(qū)
}shm_block;
int main(){
// 1. 生成共享內(nèi)存的 key
key_t key = ftok(PATHNAME,PRO_ID);
// 2. 創(chuàng)建/獲取共享內(nèi)存
int shmid = shmget(key, sizeof(shm_block),IPC_CREAT | 0666);
//3. 將共享內(nèi)存掛接到當前進程地址空間
shm_block *shm = (shm_block*)shmat(shmid,NULL,0);
//4. 打開傳輸文件
FILE *fp = fopen("input.txt","rb");
if (!fp){
perror("fopen");
exit(1);
}
// 5. 循環(huán)讀取文件并寫入共享內(nèi)存
while (1) {
int n = fread(shm->buffer,1,SZ,fp);
// 把實際讀取字節(jié)數(shù)寫 data_size
shm->data_size = n;
shm->finished = 0;
if (n == 0){
shm->finished = 1; // 設置結束標志
break;
}
// 等待讀進程消費數(shù)據(jù)
// 讀進程會在讀完后把 data_size 置為 0
while (shm->data_size != 0)
usleep(1000); // 每次休眠 1ms,避免 CPU 空轉
}
// 6. 關閉文件
fclose(fp);
// 7. 將共享內(nèi)存從當前進程分離
shmdt(shm);
return 0;
}
【圖片】