popen函数

本文详细介绍了popen函数的使用方法及原理,通过示例代码展示了如何利用popen函数执行外部命令,并实现父进程与子进程之间的单向通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

popen()函数原型如下:

        FILE *popen(const char *cmd,const char *type);

                                         返回值:若成功返回文件指针,出错则返回NULL

功能:创建一个管道,fork一个子进程,接着关闭管道的不使用端,子进程执行cmd指向的应用程序或者命令。

执行完该函数后父进程和子进程之间生成一条管道,函数返回值为FILE结构指针,该指针作为管道的一端,为父进程所拥有。子进程则拥有管道的另一端,该端口为子进程的stdin或者stdout。如果type=r,那么该管道的方向为:子进程的stdout到父进程的FILE指针;如果type=w,那么管道的方向为:父进程的FILE指针到子进程的stdin。

example:

 

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <pthread.h>
using namespace std;

//int main()
//{
//    //cout << "Hello world!" << endl;
//    FILE* fout;
//    char cmd[256]={0};
//    //puts("input a cmd!");
//    fgets(cmd,sizeof(cmd),stdin);
//    //cout << cmd;
//    fout = popen(cmd,"r");
//    if(!fout)
//        puts("popen error!");
//    char sBuf[256];
//    while(true)
//    {
//        memset(sBuf,0x00,sizeof(sBuf));
//        fgets(sBuf,sizeof(sBuf),fout);
//        if(!strlen(sBuf))
//        	break;
//        puts(sBuf);
//
//        //return 0
//
//    }
//    return 0;
//}
int main()
{
    //fopen w
    FILE * fin;
    
    char sBuf[256];
    //int nRet=pthread_create();
    while(true)
    {
    		fin = popen("sh","w");
    		if(!fin)
       		cout <<"popen error!" << endl;
        memset(sBuf,0x00,sizeof(sBuf));
        puts("input cmd:");
        fgets(sBuf,sizeof(sBuf),stdin);
        fputs(sBuf,fin);
        fputs(" > tt.txt",fin);
        fputs("exit",fin);
        system("cat tt.txt;rm tt.txt");
        pclose(fin);
    }
    return 0;
}
popen用的管道通信,所以只能读或者写,不能同时进行.

上面的popen的第一个参数可以是可执行文件,可执行文件名就是一条命令。

联想一下 find . -name *.h | grep hehe

。。。。。。。。。。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值