我的任務是使用程序創建共享內存。它將字符串從命令行參數寫入共享內存部分。它會被另一個程序讀取。我正在使用結構來創建共享內存。現在,我的問題是我無法將命令行中給出的字符串傳遞給結構變量。如何將多個字符串寫入一個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