unix网络编程----------fifo

本文展示了一个使用FIFO(命名管道)进行进程间通信的C语言程序示例。该程序由客户端和服务端组成,客户端负责输入文件路径并发送给服务端,服务端则打开文件并将内容通过FIFO返回给客户端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h>  
#include <string.h>  
#include <fcntl.h>   
#include <errno.h>  
  
#define MAXLINE 4096  

#define FIFO1 "/tmp/fifo.1"
#define FIFO2 "/tmp/fifo.2"

#define	FILE_MODE	(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
  
void client(int readfd, int writefd)  
{  
    size_t  len;  
    ssize_t n;  
    char    buff[MAXLINE];  
  
        /* 4read pathname */  
    fgets(buff, MAXLINE, stdin);  
    len = strlen(buff);     /* fgets() guarantees null byte at end */  
    if (buff[len-1] == '\n')  
        len--;              /* delete newline from fgets() */  
  
        /* 4write pathname to IPC channel */  
    write(writefd, buff, len);  
  
        /* 4read from IPC, write to standard output */  
    while ( (n = read(readfd, buff, MAXLINE)) > 0)  
        write(STDOUT_FILENO, buff, n);  
}  
  
void server(int readfd, int writefd)  
{  
    int     fd;  
    ssize_t n;  
    char    buff[MAXLINE+1];  
  
        /* 4read pathname from IPC channel */  
    if ( (n = read(readfd, buff, MAXLINE)) == 0)  
        printf("end-of-file while reading pathname");  
    buff[n] = '\0';     /* null terminate pathname */  
  
    if ( (fd = open(buff, O_RDONLY)) < 0) {  
            /* 4error: must tell client */  
        snprintf(buff + n, sizeof(buff) - n, ": can't open, %s\n",  
                 strerror(errno));  
        n = strlen(buff);  
        write(writefd, buff, n);  
  
    } else {  
            /* 4open succeeded: copy file to IPC channel */  
        while ( (n = read(fd, buff, MAXLINE)) > 0)  
            write(writefd, buff, n);  
        close(fd);  
    }  
}  

int main(int argc, char **argv)
{
	int		readfd, writefd;
	pid_t	childpid;

		/* 4create two FIFOs; OK if they already exist */
	if ((mkfifo(FIFO1, FILE_MODE) < 0) && (errno != EEXIST))
		printf("can't create %s", FIFO1);
	if ((mkfifo(FIFO2, FILE_MODE) < 0) && (errno != EEXIST)) {
		unlink(FIFO1);
		printf("can't create %s", FIFO2);
	}

	if ( (childpid = fork()) == 0) {		/* child */
		readfd = open(FIFO1, O_RDONLY, 0);
		writefd = open(FIFO2, O_WRONLY, 0);

		server(readfd, writefd);
		exit(0);
	}
		/* 4parent */
	writefd = open(FIFO1, O_WRONLY, 0);
	readfd = open(FIFO2, O_RDONLY, 0);

	client(readfd, writefd);

	waitpid(childpid, NULL, 0);		/* wait for child to terminate */

	close(readfd);
	close(writefd);

	unlink(FIFO1);
	unlink(FIFO2);
	exit(0);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值