I'm creating a parent-child process in C and these processes are using an array of characters as a shared memory and I want the execution to be in this sequence
Wait(NULL)
in parent but the execution go in the sequence of
int main(void) { if (fork( ) == 0) { //child if( (id = shmget(key, sizeof(char[n]), 0)) == -1 ) { exit(1); } shm = shmat(id, 0, 0); if (shm == (char *) -1) exit(2); .......................//some work .......................... } else //parent { if( (id = shmget(key, sizeof(char[n]), 0666 | IPC_CREAT)) == -1 ) { exit(1); } shm = shmat(id, 0, 0); //attach shared memory to pointer if (shm == (char *) -1) exit(2); //error while atatching .... ..... do { //parent turn here wait(NULL); .................................... //some work .................. } while(done!=1); shmdt(NULL); if( shmctl(id, IPC_RMID, NULL) == -1 )//delete the shared memory { perror("shmctl"); exit(-1); } } exit(0); }
You might want to call shmget(IPC_CREAT) before calling fork(), as POSIX doesn't guarentee the order of execution after the call, so the shmget() in the child process could fail because the parent hasn't had a chance to create the shared segment.
wait() waits for a child process to end. It is not used to schedule between a parent and a child process.
What, exactly, are you trying to do?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.