简体   繁体   中英

Child Process wait parent then it execute and then vice-versa in C linux

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

parent->child->parent->child->parent->child

.... and so on, i am using Wait(NULL) in parent but the execution go in the sequence of

parent->child->parent->parent->parent ....

I am trying to do this without semaphores or any ting else am still a novice Linux programmer

 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); } 
  1. 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.

  2. wait() waits for a child process to end. It is not used to schedule between a parent and a child process.

  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM