我想知道如何从客户端到守护进程共享结构?我尝试了这个,但它不起作用:
daemon.c:
int main()
{
struct data *d;
printf("shm_open\n");
if (shm_unlink("/MYSHM") != 0) {
perror("In shm_unlink()");
exit(1);
}
int fd = shm_open("/MYSHM", O_RDWR|O_CREAT, 0);
if(fd == -1) {
perror("shm_open");
return 1;
}
printf("ftruncate\n");
ftruncate(fd, sizeof(struct data));
printf("mmap\n");
d = mmap(NULL, sizeof(struct data), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
int i =0;
int j =0;
struct data *d2;
d2 = malloc(sizeof(struct data *)*950);
d2 = d;
printf("loop\n");
while(d->command[0] == NULL){
sleep(1);
}
while(strlen(d->command[j]) != 0){
if(strcmp(d2->command[i], ",") == 0){
execCmd(d2);
i = -1;
}
else{
d2->command[i] = malloc(strlen(d->command[i]));
d2->command[i] = d->command[i];
}
i++;
j++;
}
return EXIT_SUCCESS;
}
守护进程等待shm填充结构数据,然后将值分配给其他结构。
client.c:
int main(int argc, char *argv[])
{
if(argc < 2){
perror("pas assez d'arguments");
exit(EXIT_FAILURE);
}
struct data *d;
int fd;
if (shm_unlink("/MYSHM") != 0) {
printf("no shm existing");
}
if((fd = shm_open("/MYSHM", O_RDWR|O_TRUNC|O_EXCL|O_CREAT, S_IRUSR | S_IREAD| S_IWUSR | S_IWGRP | S_IXUSR |S_IEXEC | S_IRWXG)) < 0) {
perror("shm_open");
exit(EXIT_FAILURE);
}
ftruncate(fd, sizeof(struct data));
d = mmap(NULL, sizeof(struct data), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
d->pipe1 = argv[1];
d->tube2 = argv[2];
int j;
for (j = 3; j < argc; j++)
{
d->command[j - 3] = malloc((strlen(argv[j]) + strlen(argv[j]) + 1) * sizeof(char));
strcpy(d->command[j - 3], argv[j]);
}
}
客户端将结构发送给shm。