C语言创建管道实现进程间通信
2017-10-21 11:34
399 查看
#include <windows.h> #include <stdio.h> #include <stdlib.h> int runcmd( char* lpCmd ) { char buf[2048] = {0}; //缓冲区 DWORD len; HANDLE hRead, hWrite; // 管道读写句柄 STARTUPINFO si; PROCESS_INFORMATION pi; SECURITY_ATTRIBUTES sa; //ZeroMemory( buf, 2047 ); sa.nLength = sizeof( sa ); sa.bInheritHandle = TRUE; // 管道句柄是可被继承的 sa.lpSecurityDescriptor = NULL; // 创建匿名管道,管道句柄是可被继承的 if( !CreatePipe( &hRead, &hWrite, &sa, 2048 ) ) { printf( "管道创建失败!(%#X)\n", (unsigned int)GetLastError() ); return 1; } ZeroMemory( &si, sizeof( si ) ); si.cb = sizeof( si ); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdError = hWrite; si.hStdOutput = hWrite; // 创建子进程,运行命令,子进程是可继承的 if ( !CreateProcess( NULL, lpCmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi ) ) { printf( "创建进程失败!(%#x)\n", (unsigned int)GetLastError() ); CloseHandle( hRead ); CloseHandle( hWrite ); return 1; } // 写端句柄已被继承,本地需要关闭,不然读管道时将被阻塞 CloseHandle( hWrite ); // 读管道内容,并显示 while ( ReadFile( hRead, buf, 2047, &len, NULL ) ) { printf( buf ); ZeroMemory( buf, 2047 ); } CloseHandle( hRead ); return 0; } int main( int argc, char** argv ) { char cmd[256]; printf( "输入命令行:" ); gets( cmd ); runcmd( cmd ); system( "pause" ); return 0; }
相关文章推荐
- C语言创建管道实现进程间通信
- C语言无名管道实现父子进程间通信
- 进程间通信-创建管道实现机制
- c语言实现二叉树的遍历和创建程序(附带注释)
- 多线程~~简单的线程创建,C语言实现
- Linux环境编程--如何用C语言创建多进程运行以及简单的pipe管道使用
- linux 管道实现进程间通信
- 管道的创建与读写-创建两个管道来实现一个全双工通信
- C语言接口与实现创建可重用软件的技术读书笔记(1)
- 有名管道实现进程间通信。
- UNIX环境高级编程学习之第十五章进程间通信 - 通过匿名管道实现父子进程同步
- 使用无名管道pipe实现进程间通信
- C语言实现二叉查找树(搜索树)的创建,插入,查找,删除
- c语言实现文件夹的创建和删除
- Linux 上实现双向进程间通信管道
- Linux下创建管道文件,并实现两个进程间的信息传递。
- 以命名管道方式实现网络进程间通信的一个实例
- C语言实现链表的创建,初始化,插入,删除,查找