簡體   English   中英

子進程等待父級,然后執行,反之亦然

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

我正在C語言中創建一個父子進程,這些進程使用字符數組作為共享內存,我希望執行過程按此順序進行

父母->孩子->父母->孩子->父母->孩子

....依此類推,我在父級中使用Wait(NULL) ,但執行順序為

父母->孩子->父母->父母->父母....

我正在嘗試不使用信號燈或其他任何方式仍然是Linux新手

 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. 您可能想在調用fork()之前先調用shmget(IPC_CREAT),因為POSIX不能確保調用后的執行順序,因此子進程中的shmget()可能會失敗,因為父級沒有機會創建共享的細分。

  2. wait()等待子進程結束。 它不用於在父進程和子進程之間進行調度。

  3. 您到底想做什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM