popen 使用总结

函数原型:

  #include <stdio.h>
  FILE *popen( const char* command, const char* mode )

  参数说明:
  command: 是一个指向以 NULL 结束的 shell 命令字符串的指针。这行命令将被传到 /bin/sh 并使用 -c 标志,shell 将执行这个命令。

  mode: 只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 "r" 则文件指针连接到 command 的标准输出;如果 type 是 "w" 则文件指针连接到 command 的标准输入。

  返回值:
  如果调用成功,则返回一个读或者打开文件的指针,如果失败,返回NULL,具体错误要根据errno判断

  int pclose (FILE* stream)

  参数说明:
  stream:popen返回的文件指针

  返回值:

  如果调用失败,返回 -1

  作用:

  popen() 函数用于创建一个管道:其内部实现为调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程这个进程必须由 pclose() 函数关闭。

示例读:

#include <stdio.h>
#include <stdlib.h>
int main()
{


FILE *fp;
char buf[200] = {0};
if((fp = popen("ls -l /home", "r")) == NULL)
{
perror("Fail to popen\n");
exit(1);
}


while(fgets(buf, 200, fp) != NULL)
{
printf("%s", buf);
}

pclose(fp);
return 0;
}

运行:

总计 32
drwx------ 4 bob   bob     4096 07-11 14:46 bob
drwxrwxrwx 3 chong huashan 4096 07-10 15:24 chong
drwx------ 3 fz    shaolin 4096 07-10 17:49 fz
drwx------ 3 mzd   gcd     4096 07-10 15:04 mzd
drwx------ 4 samba samba   4096 07-13 09:30 samba
drwx------ 3 wgl   wgl     4096 07-10 14:13 wgl
drwx------ 3 ybq   huashan 4096 07-10 15:19 ybq
drwx------ 3 yy    yy      4096 07-10 14:49 yy

示例

管道写

#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;
}

找开test1文件即可看到

Read pipe successfully !

 


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

developer_wgl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值