[英]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 我正在C语言中创建一个父子进程,这些进程使用字符数组作为共享内存,我希望执行过程按此顺序进行
Wait(NULL)
in parent but the execution go in the sequence of
....依此类推,我在父级中使用Wait(NULL)
,但执行顺序为
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. 您可能想在调用fork()之前先调用shmget(IPC_CREAT),因为POSIX不能确保调用后的执行顺序,因此子进程中的shmget()可能会失败,因为父级没有机会创建共享的细分。
wait() waits for a child process to end. wait()等待子进程结束。 It is not used to schedule between a parent and a child process. 它不用于在父进程和子进程之间进行调度。
What, exactly, are you trying to do? 您到底想做什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.