popen函数

 

popen使用FIFO管道执行外部程序。

#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);

popen 通过type是 r 还是 w 确定command的输入/输出方向,r和w是相对command的管道而言的。r表示command从管道中读入,w表示 command通过管道输出到它的stdout,popen返回FIFO管道的文件流指针。pclose则用于使用结束后关闭这个指针。

例子一:

/*使用popen来执行“ps -ef”命令*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

#define BUFSIZE 1000

int main()
{
 FILE *fp;
 char *cmd = "ps -ef";
 char buf[BUFSIZE];
 buf[BUFSIZE] = '\0';

 /*调用popen函数执行相应的命令*/
 if((fp=popen(cmd,"r"))==NULL)
    perror("popen");
 while((fgets(buf,BUFSIZE,fp))!=NULL)
    printf("%s",buf);
 pclose(fp);
 exit(0);
}

 

例子二:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *fp;
    char buf[200] = {0};
    if((fp = popen("cat > test1", "w")) == NULL) 
    {
        perror("Fail to popen\n");
        exit(1);
    }
    fwrite("Read pipe successfully !", 1, sizeof("Read pipe successfully !"), fp);
    pclose(fp);
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值