c - 使用共享内存时出现段错误

标签 c ipc shared-memory

此代码执行以下操作: 读取“读取”文本文件的内容并将其写入共享内存空间。该代码直到昨天才工作,但今天相同的代码显示段错误。你能帮我找出我哪里出错了吗?

#include<sys/ipc.h>
#define NULL 0
#include<sys/shm.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h> 
#include<sys/wait.h> 
#include<ctype.h>
#include<fcntl.h>
#include<stdio_ext.h>

int main()
{

char *a;
char name[20];
int id,n;
char buf[50];
int fd;
fd=open("read",O_RDONLY);   
int s1=read(fd,&buf,50);

id=shmget(200,50,IPC_CREAT);

    a=shmat(id,NULL,0);
    strcpy(a,buf);
    wait(NULL);
    shmdt(a);

shmctl(id,IPC_RMID,NULL);
return 0;

 }

最佳答案

您必须检查代码中使用的每个函数的返回值。当您调用 strcpy(a,buf); 时发生段错误。如果您检查 a 的值,它没有有效的内存地址,那是因为您从未检查过 shmat() 调用返回的值,您需要仔细检查该函数所采用的参数(手册页)。

下面,我评论了发生seg错误的位置:

int main()
{
  //char name[20]; // never used
  int id; 

  char *a;
  char buf[50];
  int fd;
  fd=open("read",O_RDONLY); // check return value
  //make sure you provide the correct path for your "read" text file
  int restlt = read(fd,&buf,50); // check return value


  key_t mem_key = ftok(".", 'a');
  id = shmget(mem_key, 50, IPC_CREAT | 0666);
  //id = shmget(200,50,IPC_CREAT); //check the return value
  if (id < 0) {
      printf("Error occured during shmget() call\n");
      exit(1);
  }
  a = shmat(id,NULL,0); //check the return value
  if ((int) a == -1) {
       printf("Error occured during shmat() call\n");
       exit(1);
  }
  printf("Value of pointer a = %p \n", a);
  strcpy(a,buf); // better to use strncpy(a, buf, n);

  printf("Value of a[0]  = %c \n", *a);

  wait(NULL);
  shmdt(a);
  shmctl(id,IPC_RMID,NULL);

  return 0;

 }

查看此链接:http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/shmat.html

关于c - 使用共享内存时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60237798/

相关文章:

c - pthread_sigmask 干扰 GDB

c - 在 C 中用变量初始化数组

linux - 具有短期发布者和长期订阅者的 PUB/SUB

CUDA 共享内存占用的空间是所需空间的两倍

c++ - C/C++ - 共享内存中的环形缓冲区(POSIX 兼容)

c - 在 C 中声明字符串与整数的二维数组?

android - 在 Android 中通过 JNI 处理 GSM 调制解调器

windows - 适用于 Windows 的 D-Bus 等效项

ios - 从父应用程序发送消息到 WatchKit 接口(interface)

c++ - 我可以使用 shmctl 调整 Linux 共享内存的大小吗?