I am running into a problem when I run my a.out
file using the ./a.out
command. I am getting segmentation code error number 11. I am getting a segmentation fault when trying to access sharedMemory. I use memcpy
to paste the data into shared memory. It is Segmentation fault 11.
Am I accessing the memory correctly?
#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");
}
}
}
}
答案 0 :(得分:3)
在
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