以下是共享内存实现的程序,其中父进程和子进程将使用共享内存来打印父进程给出的下一个字母。
有一个共享内存,并且两个进程都附加到它以获得所需的结果。在我的代码中,父进程根本不执行。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
int main(int argc,char *argv[])
{
int smid;
pid_t x;
char *sm;
smid=shmget(IPC_PRIVATE,(size_t)sizeof(char),IPC_CREAT);
x=fork();
if(x>0)
{
sm=(char *)shmat(smid,NULL,0);
sprintf(sm,"%s",argv[1]);
printf("Parent wrote:\n");
puts(sm);
sleep(4);
printf("Parent got:\n");
puts(sm);
shmdt(sm);
shmctl(smid,IPC_RMID,NULL);
}
else if(x==0)
{
sleep(2);
sm=(char *)shmat(smid,NULL,0);
printf("Child read:\n");
puts(sm);
sm[0]++;
}
return 0;
}
答案 0 :(得分:2)
您在程序中有未定义的行为。您为单个字符分配内存,然后使用strcpy
,它最有可能复制更多而不是一个字符(即使它复制了一个字符,您还必须记住它还复制字符串终结者所以实际上复制了两个字符。)
未定义的行为通常是导致崩溃的主要原因,这可能是代码中发生的情况。
答案 1 :(得分:1)
这个程序的原因很多
smid=shmget(IPC_PRIVATE,(size_t)sizeof(char),IPC_CREAT);
src分配单字节,但接下来是bizzare,
char *src=(char *)malloc(sizeof(char));
strcpy(src,argv[0]); // argv[0] is more than 1
sm=(char *)shmat(smid,NULL,0);
sprintf(sm,"%s",src); // it has NULL at the end
松散修复程序..
int smid;
pid_t x;
char *sm;
smid=shmget(IPC_PRIVATE,(size_t)120*sizeof(char),IPC_CREAT|0666); // permissions and size are important
perror("smid ");
x=fork();
if(x>0)
{
char *src=(char *)malloc(120*sizeof(char)); // size is the key here
sm=(char *)shmat(smid,NULL,0);
perror("shmat" );
strcpy(src,argv[0]);
sprintf(sm,"%s",src);
printf("Parent wrote:\n");
puts(sm);
sleep(4);
printf("Parent got:\n");
puts(sm);
shmdt(sm);
shmctl(smid,IPC_RMID,NULL);
}
else if(x==0)
{
sleep(2);
sm=(char *)shmat(smid,NULL,0);
printf("Child read:\n");
puts(sm);
sm[0]++;
}