C管道通讯

/*****

linux下的pipe管道通讯

****/

#include<unistd.h>
#include<stdio.h>
#include<string.h>
#define MAXSIZE 100
int main(void)
{
int fd[2],pid,line;
char message[MAXSIZE];
if( pipe(fd) == -1 )
{
perror("create pipe failed!");
return 1;
}
else if( (pid = fork()) < 0 )
{
perror("not create a new process!");
return 1;
}
else if( pid == 0 )
{
close(fd[0]);
printf("child process send message!\n");
write(fd[1],"welcome to hello world!",22);
}
else
{
close(fd[1]);
printf("parent process receive message is:\n");
line = read(fd[0],message,MAXSIZE);
write(STDOUT_FILENO,message,line);
printf("\n");
wait(NULL);
_exit(0);
}
return 0;
}

/******

linux命名管道

****/

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#define FIFO "/tmp/fork/fifo4"

int main(void)
{
int fd;
int pid;
char r_msg[BUFSIZ];
if( (pid = mkfifo(FIFO,0777)) == -1)
{
perror("create fifo channel failed");
return 0;
}
else
printf("create success!\n");
fd = open(FIFO,O_RDWR);
if(fd == -1)
{
perror("cannot open the fifo");
return 0;
}
if(write(fd,"hello world",12) == -1)
{
perror("write data errot");
return 0;
}
else
printf("wirte data success!\n");
if(read(fd,r_msg,BUFSIZ) == -1)
{
perror("read error!\n");
return 0;
}
else
printf("the receive data is %s!\n", r_msg);
close(fd);
return 0;
}

posted on 2016-10-26 22:00  魄灠  阅读(184)  评论(0编辑  收藏  举报