#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define MAXSIZE 80
int main (int argc, char *argv[])
{
int fd[2];
pid_t pid;
char line[MAXSIZE];
int n;
if (pipe(fd) < 0)
{
perror("pipe error!");
exit(1);
}
if((pid = fork()) < 0)
{
perror("fork error!");
exit(1);
}
else if(pid > 0)
{
close(fd[0]);
write(fd[1], "hello world\n", 12);
wait(NULL);
}
else
{
close(fd[1]);
n = read(fd[0], line, MAXSIZE);
write(STDOUT_FILENO, line, n);
}
return 0;
}
2
server.c
/*server.c*/
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*定义FIFO路径*/
#define FIFO "/tmp/myfifo"
int
main (int argc, char **argv)
{
char buf_r[100];
int fd;
int nread;
/*创建FIFO管道 */
if ((mkfifo (FIFO, 0777) < 0) && (errno != EEXIST))
printf ("cannot create fifoserver\n");
printf ("Preparing for reading bytes...\n");
memset (buf_r, 0, sizeof (buf_r));
/*打开FIFO管道,不阻塞方式 */
fd = open (FIFO, O_RDONLY | O_NONBLOCK, 0);
if (fd == -1)
{
perror ("open");
exit (1);
}
while (1)
{
memset (buf_r, 0, sizeof (buf_r));
/*读管道,因为定义了非阻塞方式,故在此不会阻塞进程 */
if ((nread = read (fd, buf_r, 100)) == -1)
{
if (errno == EAGAIN)
printf ("no data yet\n");
}
printf ("read %s from FIFO\n", buf_r);
sleep (1);
}
pause ();
unlink (FIFO);
return 0;
}
/*client.c*/
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*定义FIFO路径 */
#define FIFO "/tmp/myfifo"
int
main (int argc, char **argv)
{
int i = 0;
int fd = 0;
char buf[100] = "";
int nwrite;
/*打开FIFO管道 */
fd = open (FIFO, O_WRONLY | O_NONBLOCK);
if (fd == -1)
if (errno == ENXIO)
printf ("open error; no reading process\n");
/*判断有没有参数输入 */
if (argc > 1)
printf ("Please send something\n");
/*复制参数输入 */
for (i = 1; i < argc; ++i)
{
strcat (buf, argv[i]);
strcat (buf, " ");
}
/*写到FIFO去 */
if ((nwrite = write (fd, buf, 100)) == -1)
{
if (errno == EAGAIN)
printf ("The FIFO has not been read yet.Please try later\n");
}
else
/*输出写入的内容 */
printf ("write %s to the FIFO\n", buf);
return 0;
}
第一个父子间的通信,带有亲缘关系,而且是半双工的,第二个是任意两个进程,全双工的。