UNIX环境高级编程学习之第十五章进程间通信 – 通过匿名管道实现父子进程同步
[code lang=”cpp”]/* User:Lixiujie
* Date:20100819
* Desc:通过半双工匿名管道实现父子进程同步
* File:pipePCSync.c
* gcc pipePCSync.c -o demo
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
/* 定义管道的参数文件描述符 */
static int g_pfd[2] = { -1 },g_cfd[2] = { -1 };
/* 初始化 */
void TELL_WAIT(void){
if (pipe(g_pfd) < 0 || pipe(g_cfd) < 0)
{
perror("TELL_WAIT() pipe() failed!");
exit(1);
}
}
/* 取消父进程等待 */
void TELL_PARENT(void){
if (write(g_pfd[1], "c", 1) != 1){
perror("TELL_PARENT write() failed!");
exit(1);
}
}
/* 子进程等待父进程 */
void WAIT_PARENT(void){
char c = ‘/0’;
if (read(g_cfd[0], &c, 1) != 1){
perror("WAIT_PARENT read() failed!");
exit(1);
}
if (c != ‘p’){
perror("WAIT_PARENT read data error!");
exit(1);
}
}
/* 取消子进程等待 */
void TELL_CHILD(void){
if (write(g_cfd[1], "p", 1) != 1){
perror("TELL_CHILD write failed!");
exit(1);
}
}
/* 父进程等待子进程 */
void WAIT_CHILD(void){
char c = ‘/0’;
if (read(g_pfd[0], &c, 1) != 1){
perror("WAIT_PARENT read() failed!");
exit(1);
}
if (c != ‘c’){
perror("WAIT_PARENT read data error!");
exit(1);
}
}
int main(void){
pid_t pid;
TELL_WAIT();
if ((pid = fork()) < 0){
perror("main fork() failed!");
exit(1);
}else if(0 == pid){ // Child
while (1){
printf("Child:Hello parent!/n");
TELL_PARENT();
sleep(3);
}
}else{ // Parent
while (1){
WAIT_CHILD();
printf("Parent:Hello Child!/n");
}
}
}

[/code]

发表评论