当我使用 ./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 的第一个参数必须是 struct timeval *
而不是 time_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
关于c - 使用 memcpy 后尝试获取数据的段错误 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54537686/