공유 메모리와 fork()
부모와 자식 프로세스의 계승을 계산하고 싶습니다. 내 문제는 자식 프로세스가 작동하지 않는 것 같습니다. 부모로부터 숫자를주고 싶습니다. 아이에게 그리고 아이가 계승의 결과를 부모에게 전달한 후에. 그러나 그 결과는 내가 제시 한 숫자와 동일합니다.부모와 자식 프로세스와 메모리를 공유하는 방법
나는 각 프로세스에 변수를 전달하기 위해 snprintf()
또는 spritnf()
또는 itoa()
및 atoi()
를 사용하도록 요청 받았다.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/wait.h>
#include <sys/shm.h>
int main(int argc , char *argv[])
{
int shmid,fid,status,x;
char *shm;
char *s;
int i,y,c;
key_t key=1990;
//create shared memory
shmid=shmget(1990,300,IPC_CREAT|0666);
fid=fork();
shm=shmat(shmid,NULL,0);
if(fid>0)//parent process
{
wait(&status);
s=shm;
printf("enter a number:");
scanf("%d",&x);
sprintf(s,"%d",x);//convert int to string
printf("factorial of number:%d is:%s\n",x,s);//result
shmdt(shm);
shmctl(shmid,IPC_RMID,0);
}else if(fid==0)//child process
{
shm=shmat(shmid,NULL,0);
c=atoi(s);//conver string to int
// calculate factorial
for(i=1;i<=c;i++)
{
y *=i;
}
return y;
sprintf(s,"%d",y);
shmdt(shm);
}
return 0;
}
부모는 자녀가 계산을 마칠 때까지 기다리지 않습니다. – mch
's'은 자식의 공유 메모리를 가리 키지 않습니다. –