如何通过文件记录锁实现父子进程间的同步?

摘要:父子进程间交互执行是指用一种同步原语,实现父进程和子进程在某一时刻只有一个进程执行,之后由另外一个进程执行,用一段代码举例如下: SYNC_INIT(); int i=0, counter=0; pid_t pid = fork (); i
父子进程间交互执行是指用一种同步原语,实现父进程和子进程在某一时刻只有一个进程执行,之后由另外一个进程执行,用一段代码举例如下: 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"); } 其中area是指向共享内存的一个地址,update用来增加area指向的内容(为long),在fork之后,父子进程交替更新此值。 它们使用了一些抽象的同步原语,例如SYNC_INIT用于初始化同步设施、SYNC_WAIT等待另外进程的信号、SYNC_TELL向另外进程发送信号。
阅读全文