linux共享内存写数据 没反应,Linux-C从共享内存中读取已损坏的数据

即时写入和从共享内存中读取字符串。 这里it's我的代码:Linux-C从共享内存中读取已损坏的数据

这是作家(我已经中省略无关的代码)

int main() {

char message[MAX_BUF];

key_t key;

int sharedMemoryId;

int semaphoreId;

char *vc1;

char *data;

pid_t p3;

struct sembuf operations[1];

printf("start p2\n");

saveMesageInBuffer(message); //This reads message from pipe and saves into message variable

if(message==NULL){

return -1;

}

key = getKeyForFile();

if(key != -1){

sharedMemoryId = createSharedMemoryId(key);

if(sharedMemoryId!=-1){

vc1 = shareContentInMemoryId(sharedMemoryId);

}

switch(p3 = fork()){

case -1:

printf("Error");

break;

case 0:

printf("run\n");

execl("./Ej3", "Ej3", NULL);

break;

default:

sleep(SECONDS);

writeMessageInSharedVariable(vc1, message);

pause();

break;

}

} else {

printf("Error getting key for file: %s\n", strerror(errno));

}

return 0;

}

void writeMessageInSharedVariable(char *dest, char *message){

printf("El proceso P2 (PID=%d, Ej2) transmite un mensaje al proceso P3 a traves de una variable en memoria compartida\n", getpid());

strncpy(dest, message, MAX_BUF);

}

int createSharedMemoryId(key_t key){

return shmget(key, MAX_BUF, IPC_CREAT | 0600);

}

char* shareContentInMemoryId(int memoryId){

return shmat(memoryId, (void *)0, 0);

}

key_t getKeyForFile(){

char filePath[1024];

if (getcwd(filePath, sizeof(filePath)) != NULL){

strcat(filePath, "/");

strcat(filePath, FIFO_FILE_NAME);

return ftok(filePath, 0777);

} else {

return (key_t) -1;

}

}

`

这是读者(编译为EJ3并通过fork和exec从推出作家)

int main() {

key_t key;

char message[MAX_BUF];

int sharedMemoryId;

char* vc1;

printf("el 33 \n");

key = getKeyForFile();

if(key != -1){

sharedMemoryId = createSharedMemoryId(key, sizeof(message));

sleep(3);

printf("continua\n");

vc1 = (char*)shmat(sharedMemoryId, (void *)0, 0);

if (vc1 == (char *)(-1)) {

perror("shmat");

exit(1);

}

printf("Readed %s\n", vc1);

} else {

printf("Error getting key for file: %s\n", strerror(errno));

}

}

我正在写邮件的测试,这是我读它的结果。

Readed测试[]瓦特

2017-01-04

colymore

+3

显然你缺少终止零。所以它没有被“损坏”。 –

+0

对不起,我不理解你哟 –

+3

@colymore'%s'格式用于打印一个C字符串,它是一个以空字节结尾的字节数组。你并没有在共享内存中的字符串末尾放置空字节,所以你在后面打印垃圾。 –

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值