⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 all.c

📁 用简单的例子实现了用命名管道实现进程间通信
💻 C
字号:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MESSAGE_MAX 512

int main(int argc,char *argv[])
{
        char *fifo_name;
        int res;
        int pipe_fd;
        char buffer[MESSAGE_MAX];
	
        if(argc!=2)
        {
                fprintf(stderr,"wrong command!\n");
		exit(1);
	}

       	 fifo_name = (char *)malloc(sizeof(argv[1])+15);
        strcpy(fifo_name,"/tmp/my_fifo_");
        strcat(fifo_name,argv[1]);
	
        if(access(fifo_name,F_OK) == -1)
        {
               	res = mkfifo(fifo_name,0777);
               	if(res!=0)
               	{
                        fprintf(stderr,"open computer %s unsuccessfully!\n",argv[1]);
                        exit(1);
                }
        }
        else
        {
                fprintf(stderr,"the computer %s is on!\n",argv[1]);
                exit(1);
        }

        printf("open computer %s successfully!\n",argv[1]);
	
        do
        {
                pipe_fd = open(fifo_name,O_RDONLY);
                if(pipe_fd!=-1)
                {
                        while((res = read(pipe_fd,buffer,MESSAGE_MAX))>0);
                        printf("Computer %s received:%s\n",argv[1],buffer);
                        if(strcmp(buffer,"close")==0)
                        {
                                close(pipe_fd);
                                unlink(fifo_name);
                                printf("Computer %s is closed!\n",argv[1]);
                                exit(0);
                        }
                }
                else
                {
                     fprintf(stderr,"open computer %s unsuccessfully!\n",argv[1]);
                        exit(1);
                }
        }while(1);
}

⌨️ 快捷键说明

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