这是我得到的最艰巨的任务之一:我想(需要)使用共享内存实现命名管道(例如 mkfifo 功能)。
我花了一些时间,但最后我成功实现了un-named pipe
,现在我需要完成 Named ,如上所述。
根据我的理解,Named pipe
用途mkfifo
,意思是在磁盘上创建一个文件,然后进程A
可以从命名管道读取,并且在读取时,他阻止所有其他进程写入该文件(又名命名管道)....请更正我如果我错了!?
现在,我的问题是如何使用共享内存实现命名管道?
随着un-named pipe
我打开一个共享内存段,如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024 /* make it a 1K shared memory segment */
int main(int argc, char *argv[])
{
key_t key;
int shmid;
char *data;
int mode;
if (argc > 2) {
fprintf(stderr, "usage: shmdemo [data_to_write]\n");
exit(1);
}
/* make the key: */
if ((key = ftok("shmdemo.c", 'R')) == -1) {
perror("ftok");
exit(1);
}
/* connect to (and possibly create) the segment: */
if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
perror("shmget");
exit(1);
}
/* attach to the segment to get a pointer to it: */
data = shmat(shmid, (void *)0, 0);
if (data == (char *)(-1)) {
perror("shmat");
exit(1);
}
/* read or modify the segment, based on the command line: */
if (argc == 2) {
printf("writing to segment: \"%s\"\n", argv[1]);
strncpy(data, argv[1], SHM_SIZE);
} else
printf("segment contains: \"%s\"\n", data);
/* detach from the segment: */
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}
return 0;
}
并且每次一个进程写入它而另一个进程读取它(反之亦然)。
您能解释一下我要使用的更改和/或功能吗?
请注意,我不允许使用open/close/read/write
系统调用...
非常感激