PIPE相关代码
Talk is cheap ,show me the code!
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
//authour:liyya
/*管道的读写行为
使用管道需要注意以下4种特殊情况(假设都是阻塞I/O操作,没有设置O_NONBLOCK标志):
1. 如果所有指向管道写端的文件描述符都关闭了(管道写端引用计数为0),而仍然有进程从管道的读端读数据,那么管道中剩余的数据都被读取后,再次read会返回0,就像读到文件末尾一样。
2. 如果有指向管道写端的文件描述符没关闭(管道写端引用计数大于0),而持有管道写端的进程也没有向管道中写数据,这时有进程从管道读端读数据,那么管道中剩余的数据都被读取后,再次read会阻塞,直到管道中有数据可读了才读取数据并返回。
3. 如果所有指向管道读端的文件描述符都关闭了(管道读端引用计数为0),这时有进程向管道的写端write,那么该进程会收到信号SIGPIPE,通常会导致进程异常终止。当然也可以对SIGPIPE信号实施捕捉,不终止进程。具体方法信号章节详细介绍。
4. 如果有指向管道读端的文件描述符没关闭(管道读端引用计数大于0),而持有管道读端的进程也没有从管道中读数据,这时有进程向管道写端写数据,那么在管道被写满时再次write会阻塞,直到管道中有空位置了才写入数据并返回。
*
*
*
*/
//管道不应该是有多个输入输出端,应当明确约定,是哪两个进程利用管道通信。
void sys_error(const char * error)
{
printf("%s\n",error);
exit(1);
}
void sys_info(const char *info)
{
printf("%s\n",info);
}
int main(void)
{
int fd[2]; //fd[0] -- read fd[1]--write
pid_t pid;
const char *Msg= "this is the msg stored in Pipe\n";
char buf[1024] ={0};
int res = pipe(fd);
if(res != 0)
{
sys_error(" create pipe error \n" );
}
pid = fork();
if(pid<0)
{
sys_error("fork error");
}
else if (pid == 0)
{
// child process get msg from the pipe
// wait(2);
close(fd[1]);
int len = read(fd[0],buf,sizeof(buf));
sys_info(buf);
if(len == 0)
{
close(fd[0]);
}
}
else
{
//parent process ,send msg to pipe
sys_info("start to the parent process\n");
close(fd[0]);
write(fd[1],Msg,strlen(Msg));
sleep(5);
close(fd[1]); // if fd[1] do not close, it will casue child process read is still in block mode
}
return 0;
}
FIFO READ
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
const char* START_STR="Begin:";
#define FIFO_PATH "myfifo"
const char* Msg = "this is a message that will send to the FIFO";
#define MAX_FIFO_LENGTH 1024
char buf[1024] ={0};
void sys_info(const char* info)
{
printf("%s\n",info);
}
int main(void)
{
sys_info(START_STR);
int res = mkfifo(FIFO_PATH, 0666);
if(res < 0)
{
perror("fifo");
}
int fd = open(FIFO_PATH,O_RDONLY);
if(fd<0)
{
perror("open fifo");
exit(1);
}
int length = read(fd,buf,MAX_FIFO_LENGTH);
sys_info(buf);
return 0;
}
FIFO Write
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
const char* START_STR="Begin:";
#define FIFO_PATH "myfifo"
const char* Msg = "this is a message that will send to the FIFO";
#define MAX_FIFO_LENGTH 1024
char buf[1024] ={0};
void sys_info(const char* info)
{
printf("%s\n",info);
}
int main(void)
{
sys_info(START_STR);
int res = mkfifo(FIFO_PATH, 0666);
if(0 != res)
{
perror("fifo");
}
int fifo_d = open(FIFO_PATH,O_WRONLY);
if(fifo_d < 0)
{
perror("open fifo");
exit(1);
}
sleep(1);
int length = write(fifo_d,Msg,strlen(Msg));
printf("send message to fifo\n");
return 0;
}