欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 进程间通信之socketpair

进程间通信之socketpair

2025/9/20 19:15:48 来源:https://blog.csdn.net/u011743621/article/details/148710926  浏览:    关键词:进程间通信之socketpair

进程间通信之socketpair

源代码

#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){   //保存子进程的进程idint 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;
}  

测试

[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.txtprint child process output info end...
[banting@localhost test]$ ls -tlr 

参考文献

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词