进程间通信之socketpair

进程间通信之socketpair

源代码

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>


int main()
{
    //父子通讯管道
    int m_pipe[2];
    //创建管道
    if(socketpair(AF_UNIX,SOCK_STREAM,0,m_pipe) < 0)
    {   
        printf("create socketpair pipe failed\n");  
        return -1; 
    }   
    
    //建立子进程
    pid_t pid =fork();
    //子进程创建失败
    if(pid <0) 
    {   
        close(m_pipe[0]); 
        close(m_pipe[1]); 
         return -1; 
    }   
    else if(pid == 0)
    {   
        //关闭子进程管道读端
        close(m_pipe[0]);
        //重定向标准输出到子进程管道写端
        dup2(m_pipe[1],STDOUT_FILENO);
        //重定向标准输入到子进程管道写端
        //dup2(m_pipe[1],STDIN_FILENO);
        //关闭子进程管道写端
        close(m_pipe[1]);

        //执行linux命令行
        const char* argv[] = {"ls", "-l","-a", "/home/banting/test/test_dir/",NULL};
        execvp("/usr/bin/ls",(char* const*)argv);
        //子进程结束
        return 0;
    }
    else if(pid > 0)
    {   
        //保存子进程的进程id
        int m_pid = pid;
        //关闭父进程管道的写端
        close(m_pipe[1]);
        //非阻塞等待子进程退出
        while(waitpid(m_pid,NULL,WNOHANG) == 0)
        {
            //睡眠1毫秒
            usleep(1000);
            //读取子进程的输出信息
            char buff[4096] = {0};
            int read_len = read(m_pipe[0],buff,sizeof(buff)-4);
            if(read_len <= 0)
            {
                continue;
            }
            buff[read_len] = '\0';
            //打印子进程输出信息
            printf("print child process output info begin...\n");
            printf("%s\n",buff);
            printf("print child process output info end...\n");
            return 0;
        }
    }

    return 0;
}  

测试

bash 复制代码
[banting@localhost test]$ vim test.cpp 
[banting@localhost test]$ gcc -g test.cpp -o test
[banting@localhost test]$ ./test
print child process output info begin...
total 12
drwxrwxr-x. 2 banting banting   23 Jun 17 09:56 .
drwxrwxr-x. 9 banting banting 8192 Jun 17 10:55 ..
-rw-rw-r--. 1 banting banting    0 Jun 17 09:56 test1.txt

print child process output info end...
[banting@localhost test]$ ls -tlr 

参考文献

sockpair创建双向通信的管道
dup和dup2应用及案例
Linux系统编程之exec函数族

相关推荐
Dear~yxy44 分钟前
LVS企业级实战
linux·服务器·lvs
兮动人1 小时前
Linux 安装 Claude Code 实战:Node.js、npm、GLM 配置一次跑通
linux·npm·node.js·cc·claude code
Sirius Wu2 小时前
OpenClaw Model Provider(模型提供商)完整详解
服务器·网络·人工智能·安全·aigc
2301_777998342 小时前
Linux线程控制——从线程创建到线程分离(第三部分:线程等待 pthread_join)
linux·运维·服务器·c语言·c++
谜之锋2 小时前
Linux 源码编译安装 net-snmp-5.9.1 并配置使用 SNMPv3
linux·运维·服务器·snmpv3
RuiZN3 小时前
Muduo---Channel类
运维·服务器·c++
一直在努力学习的菜鸟3 小时前
阿里云2G2核的服务器可以做什么?
linux·运维
ShineWinsu3 小时前
对于Linux:自定义协议(基于TCP)实现网络计算器的解析
linux·网络·c++·网络协议·tcp/ip·面试·网络计算器
可涵不会debug3 小时前
【LangChain系列】 零基础入门实战:从环境搭建到 LCEL 链式完整 Demo 详解
运维·服务器·langchain·vibe coding
tedcloud1233 小时前
Orca 部署指南:开源 AI 推理服务的 Linux 部署实践
linux·运维·服务器·人工智能·开源·自动化·excel