#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
/*进程间通信(IPC机制)
通信方式有: 管道 有名管道 消息队列 信号量 共享内存 套接字
管道:是一种半双工的通信方式 只能在具有亲缘关系的进程间使用
有名管道:也是半双工的通信方式,但是它允许无亲缘关系进程间的通信
*/
#if 0
//实现父子进程之间相互发送消息
int main()
{
char *parent_talk[] = {"Hello","Can you tell me,what is time?","OMG,i have to go,Bye.",NULL};
char *child_talk[] = {"Hi","No problem.","See you again.",NULL};
int fd1[2];
int fd2[2];
int res=pipe(fd1);
if(res == -1)
{
printf("create pipe error.\n");
exit(1);
}
res = pipe(fd2);
if(res == -1)
{
printf("create pipe erroe.\n");
exit(1);
}
pid_t pid;
pid = fork();
if(pid == 0) //子进程
{
close(fd1[1]);//子进程关闭fd1的写端,关闭fd2的读端
close(fd2[0]);
char buf[256];
int i;
char *talk = child_talk[i];
while(talk != NULL)
{
sleep(5);
read(fd1[0],buf,256);
printf("From Parent Msg:>%s\n",buf);
write(fd2[1],talk,strlen(talk)+1);
i++;
talk = child_talk[i];
}
close(fd1[0]);
close(fd2[1]);
}
else if(pid > 0)
{
close(fd1[0]); //父进程关闭fd1的读端,关闭fd2的读端
close(fd2[1]);
char buf[256];
int i = 0;
char *talk = parent_talk[i];
while(talk != NULL)
{
write(fd1[1],talk,strlen(talk)+1);
read(fd2[0],buf,256);
printf("From Child Msf:>%s\n",buf);
i++;
talk = parent_talk[i];
}
close(fd1[1]);
close(fd2[0]);
int status;
wait(&status);
}
return 0;
}
#endif
通信方式--管道(父子进程通信)
最新推荐文章于 2024-08-30 22:43:50 发布