【发布时间】:2020-02-15 10:18:55
【问题描述】:
此代码执行以下操作: 读取“读取”文本文件的内容并将其写入共享内存空间。代码一直工作到昨天,但相同的代码今天显示分段错误。你能帮我弄清楚我在哪里犯了错误吗?
#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;
}
【问题讨论】:
-
如果您通过验证所有函数调用的返回值来进行错误处理,您将拥有更健壮的代码并发现它更容易调试。例如,如果
open返回-1,则程序应使用perror打印错误,然后退出。 -
您确定从您的文件中读取的数据包含终止空字节吗?如果没有,您的
strcpy将溢出。改用memcpy不是更安全吗? -
另外,
wait(NULL)的意义何在?您的进程此时没有子进程,因此它只会立即返回-1(您从不检查)。这条线的目的是什么?
标签: c ipc shared-memory