打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
linux管道通信

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

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

管道用系统函数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>

7void read_pipe(int fd)

8{

9char message[100];

10 read(fd,message,100);

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

12 }

13 void write_pipe(int fd)

14 {

15 char *message="this isTuesday!\n";

16write(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 pipefailed!\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]);

40wait(&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)
{
    charmessage[100];
   read(rfd,message,100);
   printf("child process readmessage:%s",message);
    
    char*message1="from child write message!\n";
   write(wfd,message1,strlen(message1)+1);
}
void parent_rw_pipe(int rfd,int wfd)
{
    charmessage[100];
   read(rfd,message,100);
   printf("parent process readmessage:%s",message);
    
    char*message1="from parent write message!\n";
   write(wfd,message1,strlen(message1)+1);
}

int main()
{
    intpipe1[2],pipe2[2];
    intstat;
    pid_tpid;
    
   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);
    case0:
   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);
}

}

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Linux进程间通信
Linux系统管道和有名管道的通信机制
C语言进程间通信(一)
Linux的进程通讯之匿名管道
有名管道和无名管道
管道通信
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服