c - Why is the parent process not executing at all? -
following program shared memory implementation parent , child processes use shared memory printing next alphabet given parent.
there shared memory , both processes attaching obtain required result. in code, parent process not execute @ all.
#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; }
pretty cause program
smid=shmget(ipc_private,(size_t)sizeof(char),ipc_creat);
src allocated single byte follows bizzare,
char *src=(char *)malloc(sizeof(char)); strcpy(src,argv[0]); // argv[0] more 1 sm=(char *)shmat(smid,null,0); sprintf(sm,"%s",src); // has null @ end
loosely fixed program..
int smid; pid_t x; char *sm; smid=shmget(ipc_private,(size_t)120*sizeof(char),ipc_creat|0666); // permissions , size important perror("smid "); x=fork(); if(x>0) { char *src=(char *)malloc(120*sizeof(char)); // size 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]++; }
Comments
Post a Comment