Chinaunix首页 | 论坛 | 博客
  • 博客访问: 27595
  • 博文数量: 15
  • 博客积分: 530
  • 博客等级: 中士
  • 技术积分: 170
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-23 14:10
文章分类

全部博文(15)

文章存档

2011年(4)

2009年(8)

2008年(3)

我的朋友

分类: LINUX

2011-01-04 17:31:33

参考apue2的程序清单15-3,位置在apue.2e/ipc/tellwait.c

#include "apue.h"

static int    pfd1[2], pfd2[2];

void
TELL_WAIT(void)
{
    if (pipe(pfd1) < 0 || pipe(pfd2) < 0)
        err_sys("pipe error");
}

void
TELL_PARENT(pid_t pid)
{
    if (write(pfd2[1], "c", 1) != 1)
        err_sys("write error");
}

void
WAIT_PARENT(void)
{
    char    c;

    if (read(pfd1[0], &c, 1) != 1)
        err_sys("read error");

    if (c != 'p')
        err_quit("WAIT_PARENT: incorrect data");
}

void
TELL_CHILD(pid_t pid)
{
    if (write(pfd1[1], "p", 1) != 1)
        err_sys("write error");
}

void
WAIT_CHILD(void)
{
    char    c;

    if (read(pfd2[0], &c, 1) != 1)
        err_sys("read error");

    if (c != 'c')
        err_quit("WAIT_CHILD: incorrect data");
}


写一个测试程序如下


#include "ourhdr.h"
static int    pfd1[2], pfd2[2];

void
TELL_WAIT()
{
    if (pipe(pfd1) < 0 || pipe(pfd2) < 0)
        err_sys("pipe error");
}

void
TELL_PARENT(pid_t pid)
{
    if (write(pfd2[1], "c", 1) != 1)
        err_sys("write error");
}

void
WAIT_PARENT(void)
{
    char    c;

    if (read(pfd1[0], &c, 1) != 1)
        err_sys("read error");
    if (c != 'p')
        err_quit("WAIT_PARENT: incorrect data");
}

void
TELL_CHILD(pid_t pid)
{
    if (write(pfd1[1], "p", 1) != 1)
        err_sys("write error");
}

void
WAIT_CHILD(void)
{
    char    c;

    if (read(pfd2[0], &c, 1) != 1)
        err_sys("read error");
    if (c != 'c')
        err_quit("WAIT_CHILD: incorrect data");
}

static void
charatatime(char *str)
{
    char *ptr;
    int c;

    setbuf(stdout, NULL); /* set unbuffered */
    for (ptr = str; (c = *ptr++) != 0; )
         putc(c, stdout);
}

int
main(void)
{
    int        n;
    int        fd[2];
    pid_t    pid;
    char    line[MAXLINE];

    TELL_WAIT();
    if ((pid = fork()) < 0) {
        err_sys("fork error");
    } else if (pid > 0) {        /* parent */
        TELL_CHILD(pid);
        WAIT_CHILD();
        charatatime("output from parent\n");
    } else {                /* child */
        WAIT_PARENT();
        TELL_PARENT(getppid());
        charatatime("output from child\n");
    }
    exit(0);
}


shell输出

andy@andy:~/Desktop/unix$ ./wait_tell

output from child 

output from parent

andy@andy:~/Desktop/unix$ 


阅读(369) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2011-01-05 11:11:48

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com