Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1552059
  • 博文数量: 239
  • 博客积分: 1760
  • 博客等级: 上尉
  • 技术积分: 1595
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-08 23:53
文章分类

全部博文(239)

文章存档

2016年(1)

2015年(28)

2014年(53)

2013年(42)

2012年(50)

2011年(65)

分类: LINUX

2014-04-25 11:58:35

线程间通信:

点击(此处)折叠或打开

  1. #include <stdio.h> // printf
  2. #include <stdlib.h> // exit
  3. #include <unistd.h> // pipe
  4. #include <string.h> // strlen
  5. #include <pthread.h> // pthread_create
  6.   
  7. using namespace std;
  8.   
  9. void *func(void * fd)
  10. {
  11.     printf("write fd = %d\n", *(int*)fd);
  12.     char str[] = "hello everyone!";
  13.     write( *(int*)fd, str, strlen(str) );
  14. }
  15.   
  16. int main()
  17. {
  18.     int fd[2];
  19.     char readbuf[1024];

  20.     if(pipe(fd) < 0)
  21.     {
  22.         printf("pipe error!\n");
  23.     }

  24.     // create a new thread
  25.     pthread_t tid = 0;
  26.     pthread_create(&tid, NULL, func, &fd[1]);
  27.     pthread_join(tid, NULL);

  28.     sleep(3);

  29.     // read buf from child thread
  30.     read( fd[0], readbuf, sizeof(readbuf) );
  31.     printf("read buf = %s\n", readbuf);

  32.     return 0;
  33. }
输出结果:

点击(此处)折叠或打开

  1. write fd = 4
  2. read buf = hello

进程间通信:

点击(此处)折叠或打开

  1. #include <stdio.h> // printf
  2. #include <stdlib.h> // exit
  3. #include <unistd.h> // pipe
  4. #include <string.h> // strlen
  5. #include <pthread.h> // pthread_create

  6. using namespace std;

  7. int main()
  8. {
  9.     int fd[2];
  10.     int pid = 0;
  11.     char str[] = "hello";
  12.     char readbuf[1024];

  13.     if(pipe(fd) < 0)
  14.     {
  15.         printf("pipe error!\n");
  16.     }

  17.     if((pid = fork()) < 0)
  18.     {
  19.         printf("fork error!\n");
  20.     }
  21.     else if(pid == 0)
  22.     {
  23.         printf("child process!\n");

  24.         // close read channel
  25.         close(fd[0]);
  26.         write(fd[1], str, strlen(str));
  27.     }
  28.     else
  29.     {
  30.         printf("father process!\n");

  31.         // close write channel
  32.         close(fd[1]);
  33.         read(fd[0], readbuf, sizeof(readbuf));
  34.         printf("readbuf = %s\n", readbuf);
  35.     }

  36.     return 0;
  37. }
输出结果:

点击(此处)折叠或打开

  1. father
  2. child
  3. readbuf = hello

转载自:http://blog.csdn.net/robertkun/article/details/8095331

阅读(4161) | 评论(0) | 转发(0) |
0

上一篇:Linux编程获取文件属性

下一篇:linux 管道

给主人留下些什么吧!~~