我的任务是使用程序创建共享内存。它将字符串从命令行参数写入共享内存部分。它会被另一个程序读取。我正在使用结构来创建共享内存。现在,我的问题是我无法将命令行中给出的字符串传递给结构变量。如何将多个字符串写入一个char变量指针数组?如何使用指针数组将多个字符串存储到结构中
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <malloc.h>
#include "shm-com.h"
void main(int argc,char *argv[])
{
key_t shmKey;
int shm_id,i,j=0;
struct memory *dataptr;
char *string[10];
shmKey = ftok(".",1234);
printf("no. of strings %d\n",argc);
shm_id = shmget(shmKey,sizeof(struct memory),0666 | IPC_CREAT);
if(shm_id < 0)
{
perror("shm_id didn't create\n");
exit(0);
}
dataptr = (struct memory *)shmat(shm_id,NULL,0);
if((int) dataptr == -1)
{
perror("****didn't attatch to share memory\n");
}
printf("share memory attatched at %p address\n",dataptr);
dataptr->status = NOT_READY;
for(i = 1;i < argc;i++)
{
string[j] = argv[i];
j++;
}
printf("data attached to share memory\n");
for(i = 0;i < argc ; i++)
{
printf("%s\n",string[i]);
}
for(i = 0;i < argc;i++)
{
strcpy(dataptr->data[i],argv[i]);
}
dataptr->status = FILLED;
printf("please start client window\n");
while(dataptr != TAKEN);
sleep(1);
shmdt((void *)dataptr);
printf("server has detached sharre memory\n");
shmctl(shm_id,IPC_RMID,NULL);
printf("server cancelled shared memroy\n");
exit(0);
}
和我的结构文件名SHM-com.h是
#define TAKEN 1
#define FILLED 0
#define NOT_READY -1
struct memory
{
char *data[10];
int status;
};
你可能笏使用某种共享的信号或自旋锁,而不是简单的“INT状态”它有助于避免竞争条件和可能比检查更efficint休眠循环。 – Jasen