命名管道实现进程同步

命名管道

主要原理就是实现了生产者消费者问题,实现进程同步功能。为啥要用命名管道呢?就是想摆脱管道的束缚,实现任意进程间的通信。

代码如下


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <cassert>
#include <fcntl.h>
#include <csignal>
#include <iostream>

#define PIPE_SYNC "/tmp/syncfifo"
#define FILE_MODE  (0666)

//#define FILE_MODE  (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)


typedef struct{
  pid_t pid;
}StorePid;

bool create_sync_pipe()
{
    if (access(PIPE_SYNC, F_OK) == -1)
    {
        int ret = mkfifo(PIPE_SYNC, FILE_MODE);
        if (ret != 0){
            printf("Create PIPE_SYNC fail (%s) (%d)\n", __func__, __LINE__);
            unlink(PIPE_SYNC);
            return false;
		}
    }else{
        printf(" PIPE_SYNC exist (%s) (%d)\n", __func__, __LINE__);
		chmod(PIPE_SYNC, FILE_MODE);
	}

    return true;

}
bool del_sync_pipe()
{
    if (access(PIPE_SYNC, F_OK) != -1){
      printf(" PIPE_SYNC exist del it (%s) (%d)\n", __func__, __LINE__);
      unlink(PIPE_SYNC);
	}

    return true;
}

void signalHandler( int signum )
{
    printf("Interrupt signal (%d) received.\n",signum);
    del_sync_pipe();
    // cleanup and close up stuff here  
    // terminate program  
   exit(signum);  
}


bool send_cudapid(StorePid* params)
{
    if (params == nullptr)
        return false;

    if (access(PIPE_SYNC, F_OK) == -1){
        printf(" PIPE_SYNC not exist (%s) (%d)\n", __func__, __LINE__);
	    assert(0);
	    return false;
	}


    int pipe_fd = open(PIPE_SYNC, O_WRONLY);
    if (pipe_fd != -1)
    {
        int ret = write(pipe_fd, params, sizeof(StorePid));
        if (ret == -1)
        {
            printf("[%s][%d][ Send_cudapid fail!][ret:%d]\n", __func__, __LINE__, ret);
        }
        else
        {
            close(pipe_fd);
#ifdef CS_DEBUG
            printf("[%s][%d][Send_cudapid  success ][ret:%d]\n", __func__, __LINE__, ret);
#endif
        }
    }
    else
    {
        printf("[%s][%d][open PIPE_SYNC  fail!][ret:%d]\n", __func__, __LINE__, pipe_fd);
        return false;
    }

    return true;
}

bool get_cudapid(StorePid* data)
{
    if (data == nullptr)
        return false;

    if (access(PIPE_SYNC, F_OK) == -1){
        printf(" PIPE_SYNC not exist (%s) (%d)\n", __func__, __LINE__);
	    assert(0);
	    return false;
	}

    int ret;
    int pipe_fd = open(PIPE_SYNC, O_RDONLY);
    if (pipe_fd != -1)
    {
        do
        {
            ret = read(pipe_fd, data, sizeof(StorePid));
#ifdef CS_DEBUG
            printf("[%s][%d][read PIPE_SYNC ][ret:%d][pid:%d]\n", __func__, __LINE__, ret, getpid());
#endif
        } while (ret != sizeof(StorePid));
        close(pipe_fd);
#ifdef CS_DEBUG
        printf("[%s][%d][Get_cudapid success begin exe cuda process!]\n", __func__, __LINE__);
#endif
    }
    else
    {
        printf("[%s][%d][open PIPE_SYNC fail!]\n", __func__, __LINE__);
        return false;
    }

    return true;
}

bool send_msg_to_exe_cuda(void)
{
    if (access(PIPE_SYNC, F_OK) == -1){
        printf(" PIPE_SYNC not exist (%s) (%d)\n", __func__, __LINE__);
	    assert(0);
	    return false;
	}

    char buff    = 1;
    int  pipe_fd = open(PIPE_SYNC, O_WRONLY);

    if (pipe_fd != -1)
    {
        int ret = write(pipe_fd, &buff, 1);
        if (ret == -1)
        {
            printf("[%s][%d][write PIPE_SYNC fail!][ret:%d]\n", __func__, __LINE__, ret);
            return false;
        }
        else
        {
            close(pipe_fd);
#ifdef CS_DEBUG
            printf("[%s][%d][write PIPE_SYNC success ][ret:%d]\n", __func__, __LINE__, ret);
#endif
        }
    }
    else
    {
        printf("[%s][%d][opene PIPE_SYNC  fail!][ret:%d]\n", __func__, __LINE__, pipe_fd);
        return false;
    }

    return true;
}

bool get_msg_to_exe_cuda(void)
{
    char buffer = 0;
    int  ret;

    if (access(PIPE_SYNC, F_OK) == -1){
        printf(" PIPE_SYNC not exist (%s) (%d)\n", __func__, __LINE__);
	    assert(0);
	    return false;
	}

    int pipe_fd = open(PIPE_SYNC, O_RDONLY);
    if (pipe_fd != -1)
    {
        do
        {
            ret = read(pipe_fd, &buffer, 1);
#ifdef CS_DEBUG
            printf("[%s][%d][read PIPE_SYNC][ret:%d][pid:%d]\n", __func__, __LINE__, ret, getpid());
#endif
        } while (ret != 1 || buffer == 0);
        close(pipe_fd);
#ifdef CS_DEBUG
        printf("[%s][%d][get msg success begin exe cuda process!]\n", __func__, __LINE__);
#endif
        return true;
    }
    else
    {
        printf("[%s][%d][open pipe fail,pid:%d exit!]\n", __func__, __LINE__, getpid());
        return false;
    }
}

int main()
{
  pid_t pid;
  signal(SIGINT, signalHandler); 

  if(!create_sync_pipe()){
    printf("[%s][%d]\n",__func__,__LINE__);
    return 1;
  }

  pid = fork();

  if(pid == 0){
    StorePid data;
	data.pid = getpid();

	if(send_cudapid(&data)){
        printf("[%s][%d] send pid success pid:%d\n",__func__,__LINE__,data.pid);
	}
    //sleep(1);
	if(get_msg_to_exe_cuda()){
        printf("[%s][%d] get mesg success begin to .........\n",__func__,__LINE__);

       sleep(3);
       del_sync_pipe();
	   exit(0);
      //while(1);
	}
	exit(1);


  }
  else{
    //sleep(5);
	StorePid pdata;

	if(get_cudapid(&pdata)){
        printf("[%s][%d] parent get pid:%d\n",__func__,__LINE__,pdata.pid);
	}

    //sleep(1);
	if(send_msg_to_exe_cuda()){
        printf("[%s][%d] send mesg success begin to .........\n",__func__,__LINE__);
	}

    //del_sync_pipe();
	waitpid(pid,NULL,0);
  }

  return 0;
}


执行结果

在这里插入图片描述

注意问题

(1)这里我们创建的管道文件/tmp/syncfifo 每次创建然后删除,不能保证一些异常情况下代码会正常执行,导致创建的文件不能删除,这样如果换了用户,执行可能会有文件权限的问题,导致open文件打不开。为什么会这样呢?其实我们创建的问题件权限0666是所有用户所有用户组都有读写权限。但是由于系统下umask 机制,导致创建的文件权限并不是0666。具体当前用户umask是啥,用umask查看,如下图所示:

普通用户

在这里插入图片描述
创建后的文件权限会减去umask的值,因此最终创建的文件权限如下图所示
在这里插入图片描述

su用户:

在这里插入图片描述
在这里插入图片描述

注册异常处理handler函数

用户态实现注册异常处理,比如ctr +c 等信号的处理事件
signal(SIGINT, signalHandler);
SIGINT 为信号向量,signalHandler为回调函数,本文中防止ctr+c 程序元异常退出导致管道文件没有删除,所以在回调里面也调用了删除管道的函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Windows 中,可以使用命名管道(Named Pipes)实现进程间通信。以下是一些基本步骤: 1. 创建命名管道 使用 CreateNamedPipe 函数创建一个命名管道。该函数需要指定管道名称、管道的读写模式、管道的最大实例数等参数。 2. 等待客户端连接 使用 ConnectNamedPipe 函数等待客户端的连接。该函数会一直阻塞,直到有客户端连接成功。 3. 接收客户端数据 使用 ReadFile 函数从管道中读取客户端发送的数据。 4. 发送数据给客户端 使用 WriteFile 函数向管道中写入数据,以便客户端读取。 5. 断开连接 使用 DisconnectNamedPipe 函数断开与客户端的连接。如果需要与多个客户端通信,则返回第 2 步。 6. 关闭管道 使用 CloseHandle 函数关闭命名管道的句柄。 注意事项: - 在创建管道时,需要指定管道名称,该名称在系统中必须是唯一的。 - 管道支持同步和异步方式进行读写操作,可以根据具体需求选择使用哪种方式。 - 管道的读写操作是阻塞式的,也可以使用 overlapped 结构体实现异步操作。 下面是一个简单的代码示例,演示如何使用命名管道实现进程间通信: ``` #include <windows.h> #include <stdio.h> #define PIPE_NAME "\\\\.\\pipe\\MyPipe" int main() { HANDLE hPipe; char buffer[1024]; DWORD dwRead; // 创建命名管道 hPipe = CreateNamedPipe(PIPE_NAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 0, 0, 0, NULL); if (hPipe == INVALID_HANDLE_VALUE) { printf("CreateNamedPipe failed! Error code: %d\n", GetLastError()); return 1; } // 等待客户端连接 if (!ConnectNamedPipe(hPipe, NULL)) { printf("ConnectNamedPipe failed! Error code: %d\n", GetLastError()); return 1; } // 接收客户端数据 if (!ReadFile(hPipe, buffer, sizeof(buffer), &dwRead, NULL)) { printf("ReadFile failed! Error code: %d\n", GetLastError()); return 1; } printf("Received data from client: %s\n", buffer); // 发送数据给客户端 if (!WriteFile(hPipe, "Hello, client!", 15, NULL, NULL)) { printf("WriteFile failed! Error code: %d\n", GetLastError()); return 1; } // 断开连接 DisconnectNamedPipe(hPipe); // 关闭管道 CloseHandle(hPipe); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值