通过管道与子进程通信

通过管道与子进程通信

 

转载时请注明出处:http://blog.csdn.net/absurd/

 

最近要把mplayer改造成C/S架构的,mplayer比较复杂,为了避免修改mplayer的代码,我决定让mplayer作为Server的子进程来运行,两者之间用管道作为通信方式。通过管道与子进程通信实现很简单,但从来没有用过,还是折腾了好一会儿才搞定,这里做个笔记,供以后查阅。

parent.c

#include <unistd.h>

 

int main(int argc, char* argv[])

{

    int parent_to_child[2] = {0};

    int child_to_parent[2] = {0};

 

    pipe(parent_to_child);

    pipe(child_to_parent);

 

    if(fork() == 0)

    {

        close(parent_to_child[1]);

        close(child_to_parent[0]);

 

        dup2(parent_to_child[0], STDIN_FILENO);

        dup2(child_to_parent[1], STDOUT_FILENO);

 

        execl("./child.exe", "./child.exe", NULL);

    }

    else

    {

        char message[32] = {0};

        close(parent_to_child[0]);

        close(child_to_parent[1]);

 

        fprintf(stderr, "parent:%d/n", getpid());

        while(1)

        {

            write(parent_to_child[1], "to-c", 4);

            read(child_to_parent[0], message, 4);

 

            fprintf(stderr, "pid=%d: %s/n", getpid(), message);

            if(strcmp(message, "quit") == 0)

            {

               break;

            }

        }

    }

   

    return 0;

}

                                    

child.c

#include <stdio.h>

#include <unistd.h>

 

int main(int argc, char* argv[])

{

    int i = 0;

    char message[32] = {0};

 

    fprintf(stderr, "child:%d/n", getpid());

 

    for(i = 0; i < 8; i++)

    {

        write(STDOUT_FILENO, "to-p", 4);

        read(STDIN_FILENO, message, 4);

        fprintf(stderr, "pid=%d: %s/n", getpid(), message);

    }

 

    write(STDOUT_FILENO, "quit", 4);

 

    return 0;

}

 

Makefile

ll:

    gcc -g parent.c -o parent.exe

    gcc -g child.c -o child.exe

clean:

    rm -f *.exe

运行测试

[root@localhost pipe]# ./parent.exe

parent:3058

child:3059

pid=3058: to-p

pid=3059: to-c

pid=3058: to-p

pid=3059: to-c

pid=3058: to-p

pid=3059: to-c

pid=3058: to-p

pid=3059: to-c

pid=3058: to-p

pid=3059: to-c

pid=3058: to-p

pid=3059: to-c

pid=3058: to-p

pid=3059: to-c

pid=3058: to-p

pid=3059: to-c

pid=3058: quit

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值