gpt4 book ai didi

c - 尝试复制共享内存地址时出现段错误

转载 作者:行者123 更新时间:2023-11-30 18:32:14 24 4
gpt4 key购买 nike

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<string.h>
#include<malloc.h>

int main(int argc,char* argv[]){
/* Initialise the variables */
int key,shmid,fd1,bytes_written;
char *shmptr = NULL;
char *buff = NULL;
key = shmid = fd1 = bytes_written = 0;

/*Validate the i/p parameter*/
if(argc < 2){
printf("Enter the Output file");
return -1;
}
printf("\n The Output File is : %s \n",argv[1]);

/* Open the file in write mode */
fd1 = open(argv[1],O_WRONLY);
if(fd1 == -1){
printf("\n File cannot be opened! \n");
return -1;
}

/* Create the shared memory key */
key = ftok(".",12);

/* create the shared memory segment */
shmid = shmget(key,1000,0);

/* Attach with the shared memory segment
** get the pointer to the shared address
*/
#if 0
buff = (char *)malloc((sizeof(char) * 1000));
if(NULL == buff){
printf("\n Unable to allocate the memory! \n");
return -1;
}
#endif

shmptr = shmat(shmid,0,0);
buff = shmptr;
//memcpy(buff,shmptr,1000);
printf("\n %s \n",buff);

/* Write the contents into the file */
bytes_written = write(fd1,buff,1000);
if(bytes_written == -1){
printf("\n Write operation is not successfull! \n");
return -1;
}

/* Detach from the shared memory */
shmdt(shmptr);
//free(buff);

return 0;
}

我想将共享内存中的内容复制到缓冲区,然后将数据写入文件。当我尝试执行 buff = shmptr;

时遇到段错误

最佳答案

验证您的 shmget() 和 shmat() 结果。可能他们返回 -1 并且您尝试访问无效的内存位置。

关于c - 尝试复制共享内存地址时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15493691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com