父子进程间交互执行是指用一种同步原语,实现父进程和子进程在某一时刻只有一个进程执行,之后由另外一个进程执行,用一段代码举例如下:
SYNC_INIT(); int i=0, counter=0; pid_t pid = fork (); if (pid < 0) err_sys ("fork error"); else if (pid > 0) { // parent for (i=0; i<NLOOPS; i+=2) { counter = update ((long *)area); if (counter != i) err_quit ("parent: expected %d, got %d", i, counter); else printf ("parent increase to %d based %d\n", i+1, counter); SYNC_TELL(pid, 1); SYNC_WAIT(0); } printf ("parent exit\n"); } else { for (i=1; i<NLOOPS+1; i+=2) { SYNC_WAIT(1); counter = update ((long *)area); if (counter != i) err_quit ("child: expected %d, got %d", i, counter); else printf ("child increase to %d based %d\n", i+1, counter); SYNC_TELL(getppid (), 0); } printf ("child exit\n"); }