共有メモリとfork()
親プロセスと子プロセスで階乗を計算したいと思っています。私の問題は子プロセスが機能していないようですが、親から数値を渡したい子に、そして、子が階乗の結果を親に渡した後。しかし結果は私が与えた数と同じです。cで親プロセスと子プロセスを共有する方法
変数を各プロセスに渡すために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'は子の共有メモリを指しません。 –