c - 分段错误 11 尝试使用 memcpy 后获取数据
问题描述
使用命令运行a.out
文件时遇到问题。./a.out
我收到分段代码错误号 11。我在尝试访问 sharedMemory 时遇到分段错误。我用来memcpy
将数据粘贴到共享内存中。这是分段错误 11。
我是否正确访问内存?
#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<unistd.h>
#include<time.h>
int main(){
pid_t childPid;
childPid = fork();
char *shm;
if(childPid == 0){
char *args[] ={"ls","-l",NULL};
int shmid;
int shsize = 100;
key_t key;
char *s;
key = 9876;
shmid = shmget(key,shsize, IPC_CREAT | 0666);
if(shmid < 0){
printf("error getting shmid");
exit(1);
}
shm = shmat(shmid,NULL,0);
if(shm == (char *) -1){
printf("error getting shared memory");
exit(1);
}
time_t startTime;
gettimeofday(&startTime,0);
memcpy(shm,&startTime,sizeof(startTime));
time_t endTime;
execvp(args[0],args);
printf("successfuly created child proceess");
exit(0);
}
else if (childPid <0){
printf("unsuccessfuly created child proccess");
else{
int returnStatus;
waitpid(childPid,&returnStatus,0);
if(returnStatus == 0){
printf("The child terminated normally");
printf("%s",*shm);
}
if(returnStatus == 1){
printf("The child terminated with error");
}
}
}
}
解决方案
在
time_t startTime;
gettimeofday(&startTime,0);
gettimeofday的第一个参数必须是 astruct timeval *
不是 atime_t *
所以
struct timeval startTime;
gettimeofday(&startTime,0);
在
char *shm;
...
printf("%s",*shm);
您不能取消对shm的引用,因为目前它的第一个字符的 ascii 代码被用作字符串的地址,必须是
char *shm;
...
printf("%s",shm);
后
else if (childPid <0){
printf("unsuccessfuly created child proccess");
}
缺少一个
我鼓励你编译要求编译器产生警告,使用gcc使用选项-pedantic -Wall
推荐阅读
- r - 根据日期拆分组内的重叠行
- php - html表格背景图像不起作用
- php - 将值动态存储到数组的另一种方法是使用不推荐使用的代码来执行相同的操作
- webrtc - DOMException: 无法启动视频源
- javascript - Object.assign() ,合并/覆盖键,复制数组的值以创建对象
- c# - 如何使用 Lambda 表达式 c# 在一个列表中为与另一个列表中的 Id 匹配的 Id 设置标志
- android - 如何解决使用 volley 解析登录 json 的问题?
- c# - 为已自动激活的 ComponentRegistration 添加激活事件
- php - office365 php中的批处理请求给出了错误的请求
- c# - 如何重新实现电子邮件的可扩展功能