这一章节我们主要讲进程间的通信,主要方式大概有管道、信号量、消息列队、共享内存等。
首先讲管道,管道分为有名管道、无名管道。其中有名管道是用于父进程和子进程之间的通信,太过于局限。有名管道强大一些,可用于不相关 的进程之间的通信。
无名管道
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc,char *argv)
{
int pipe_fd[2];
char buf[5];
pid_t cpid;
if(pipe(pipe_fd)==-1)
{
printf("create error\r\n");
exit(1);
}
cpid=fork();
if(cpid==-1)
{
printf("create error\r\n");
exit(1);
}
if(cpid==0)
{
sleep(2);
close(pipe_fd[0]);
write(pipe_fd[1],"12345",5);
}
else
{
sleep(3);
close(pipe_fd[1]);
read(pipe_fd[0],buf,5);
printf("buf is %s \r\n",buf);
}
}
有名管道
这里编写两个程序 进行通信
//读
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#define FIFO "/tmp/myfifo"
int main(int argc,char *argv)
{
char buf[100];
int fd;
if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)
{
printf("printf create fail\r\n");
}
memset(buf,0,sizeof(buf));
fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
if(fd==-1)
{
printf("open:");
exit(1);
}
while(1)
{
if(read(fd,buf,100)==-1)
{
printf("no data\r\n");
}
else
{
printf("buf is %s\r\n",buf);
}
}
pause();
ulink(FIFO);
}
//写
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define FIFO "/tmp/myfifo"
/* 使用带参的 main 函数是因为要用户输入要写入的内容 */
int main(int argc,char **argv)
{
int fd;
char buf_w[100];
int nwrite;
/* 打开 FIFO 管道,并设置非阻塞标志 */
432
fd=open(FIFO,O_WRONLY|O_NONBLOCK,0);
if(fd==-1)
{
if(errno==ENXIO)
printf("open error:no reading process");
}
if(argc==1)
{
printf("Plese sent something\n");
}
/* 将用户输入的数据先拷贝到 buf_w 缓冲区中 */
strcpy(buf_w,argv[1]);
/* 向管道中写入字符串 */
if((nwrite=write(fd,buf_w,100))==-1)
{
if(errno==EAGAIN)
printf("The FIFO has not been read yet.Please try latter.\n");
}
else
{
printf("write %s to the FIFO\n",buf_w);
}
}