通过管道与子进程通信
转载时请注明出处: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