linux管道通信 半双工通信

来源:互联网 发布:跆拳道功夫大师软件 编辑:程序博客网 时间:2024/05/22 04:44

本文转载自:http://blog.sina.com.cn/s/blog_5ed3e6210100d87d.html



windows里进程间的通信主要用到是的消息,而在Linux里管道通信是一个不错的选择。总是觉得在Linux里编程总是让人感觉一目了然。不像在windows里,用个变量的类型都要想变天。

管道分两处,有名的和无名的,无名的叫管道,有名的叫有名管道。两种管道的区别在于一个有名称,一个无名称。管道只能用于有亲系关系的进程间通信,即只能在父进程与子进程或兄弟进程间通信。而有名管道可以用于任何进程间通信。管道有半双工的,即在某一时刻只能有一个进程向管道里读或写。管道因为没有名字所有管道的缓冲大小是受到系统的限制的,不同的系统管道的缓冲大小 是不相同的。可以在/usr/include/linux/limits.h里查看PIPE_BUF的大小 ,在我的系统里为3 #define PIPE_BUF 4096

管道用系统函数pipe()来创建。用man pipe可得到:

#include <unistd.h>

int pipe(int pipefd[2]);

有一个参数,是一个整形的有两个元素的数组。pipefd[0]是读端,pipefd[1]是写端。看具体怎么创建一个pipe;

1 #include<unistd.h>

2 #include<stdio.h>

3 #include<string.h>

4 #include<sys/types.h>

5 #include<stdlib.h>

6 #include<sys/wait.h>

7 void read_pipe(int fd)

8 {

9 char message[100];

10 read(fd,message,100);

11 printf("read pipe message:%s",message);

12 }

13 void write_pipe(int fd)

14 {

15 char *message="this is Tuesday!\n";

16 write(fd,message,strlen(message)+1);

17 }

18 int main()

19 {

20 int fd[2];

21 pid_t pid;

22 int stat_val;

23 if(pipe(fd))

24 {

25 printf("create pipe failed!\n");

26 }

27 pid=fork();

28 switch(pid)

29 {

30 case -1:

31 printf("fork error!\n");

32 break;

33 case 0:

34 close(fd[1]);

35 read_pipe(fd[0]);

36 break;

37 default:

38 close(fd[0]);

39 write_pipe(fd[1]);

40 wait(&stat_val);

41 break;

42 }

43

44 }

~ 先定义读端,在读端里用read()函数把管道里的数据读出message里,然后打印出Message

然后定义写端,在写端里用write()向pipe里写入字符串。在Main里要先在父进程里用pipe()创建一个管道,然后再用fork()创建一个子进程。

接着用一个switch来判断是父进程还是子进程在进行操作。在子进程里,要读管道里的数据先要把父进程里的写端关闭,即关闭fd[1]。然后开始读数据,如果是父进程要写入数据,则要先关闭读端。

要进行全双工的读与写,则要用两个管道里实现。看下面:

#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>
#include<stdlib.h>

void child_rw_pipe(int rfd,int wfd)
{
    char message[100];
    read(rfd,message,100);
    printf("child process read message:%s",message);
    
    char *message1="from child write message!\n";
    write(wfd,message1,strlen(message1)+1);
}
void parent_rw_pipe(int rfd,int wfd)
{
    char message[100];
    read(rfd,message,100);
    printf("parent process read message:%s",message);
    
    char *message1="from parent write message!\n";
    write(wfd,message1,strlen(message1)+1);
}

int main()
{
    int pipe1[2],pipe2[2];
    int stat;
    pid_t pid;
    
    if(pipe(pipe1))
{
    printf("create pipe1 failed!\n");
    exit(1);
}
    if(pipe(pipe2))
{
    printf("create pipe2 failed!\n");
    exit(1);
}
    pid=fork();
    switch(pid)
{
    case -1:
    printf("error fork!\n");
    exit(1);
    case 0:
    close(pipe1[1]);
    close(pipe2[0]);
    child_rw_pipe(pipe1[0],pipe2[1]);
    exit(0);
    default:
    close(pipe1[0]);
    close(pipe2[1]);
    parent_rw_pipe(pipe1[1],pipe2[0]);
    wait(&stat);
    exit(0);
}

}
原创粉丝点击