test11~1.txt

来自「Linux下的C语言编程」· 文本 代码 · 共 118 行

TXT
118
字号
/*服务器端*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdarg.h>
#include <fcntl.h>

#define BUF_SIZE 1024
#define MYKEY 24

int main(void)
{
	int shmid;
	char *shmptr;
	int fdin,fdout;
	char ch='w';
   
	if(mkfifo("fifo1",0600)==-1|| mkfifo("fifo2", 0600)==-1)
	{
		printf("error, failed to creat my-fifo!\n");
		exit(254);
	}

	if((fdout=open("fifo1", O_WRONLY)==-1)|| (fdin=open("fifo2", O_RDONLY)==-1))
	{
		printf("error, failed to open my-fifo!\n");
		exit(254);
	}

	if(shmid=shmget(MYKEY, BUF_SIZE, IPC_CREAT)==-1)
	{
        	printf("shmget error! \n");
	        exit(1);
	}
    
	if(shmptr=shmat(shmid,0,0)==( void*)-1)
	{
    		fprintf(stderr, "shmat error!\n");
		exit(1);
	}

	while(1)
	{
	    	while(ch!='s')
    		{
		        read(fdin, &ch, 1);
		}
		printf("string: %s \n", shmptr);
		if(write(fdout, "p", 1)!=1)
		{
		        fprintf(stderr, "write error.\n");
		        exit(1);
		}
		ch='w';
	}

}

/*客户端*/

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUF_SIZE 1024
#define MYKEY 24

int main(void)
{
    	int shmid;
    	char *shmptr;
    	int fdin, fdout;
    	char ch='w';
   
	if((fdout=open("fifo2", O_WRONLY)==-1)|| (fdin=open("fifo1", O_RDONLY)==-1))
	{
		printf("error, failed to open my-fifo!\n");
		exit(254);
	}

    	if(shmid=shmget(MYKEY, BUF_SIZE, IPC_CREAT)==-1)
    	{
        	printf("shmget error! \n");
        	exit(1);
    	}
    
	if(shmptr=shmat(shmid,0,0)==( void*)-1)
	{
    		fprintf(stderr, "shmat error!\n");
    		exit(1);
	}

	scanf("input string: %s \n", shmptr);

	while(1)
	{
    		while(ch!='p')
    		{
        		read(fdin, &ch, 1);
     		}
    		scanf("\ninput string: %s \n", shmptr);
    		if(write(fdout, "s", 1)!=1)
    		{
        		fprintf(stderr,"write error.\n");
        		exit(1);
    		}
    		ch='w';
    
	}

	exit(0);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?