c 子程序语言,C 语言使用popen() 执行子程序

除了使用system()外 使用popen()也可以执行子程序

#include

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

int pclose(FILE *stream);

执行popen()会等待调用的子程序结束,才执行后续的代码。

【验证步骤】

1.创建子程序

syscall.c

#include

int main()

{

int cnt = 0;

while(++cnt < 20)

{

sleep(1);

printf("loop:%d\n",cnt);

}

}

编译 gcc syscall.c -o syscall ; 生成可执行程序 syscall

2.创建测试主程序

test.c

#include

#include

#include

#include

void test_popen(const char *name)

{

FILE *fp;

char buffer[64] = {'\0'};

fp = popen(name, "r");

if(NULL == fp)

{

printf("popen failed!!!\n");

return;

}

while(fgets(buffer, sizeof(buffer), fp))

{

printf("test_popen get:%s\n", buffer);

}

pclose(fp);

}

int main()

{

time_t now = time(NULL);

printf("enter:main -- %s\n", ctime(&now));

test_popen("./syscall");

now = time(NULL);

printf("leave:main -- %s\n",ctime(&now));

return 0;

}

编译 gcc test.c ; 生成可执行程序 a.out

运行主程序看验证结果

./a.out

enter:main -- Wed May 8 19:12:45 2019

test_popen get:loop:1

test_popen get:loop:2

test_popen get:loop:3

test_popen get:loop:4

test_popen get:loop:5

test_popen get:loop:6

test_popen get:loop:7

test_popen get:loop:8

test_popen get:loop:9

test_popen get:loop:10

test_popen get:loop:11

test_popen get:loop:12

test_popen get:loop:13

test_popen get:loop:14

test_popen get:loop:15

test_popen get:loop:16

test_popen get:loop:17

test_popen get:loop:18

test_popen get:loop:19

leave:main -- Wed May 8 19:13:04 2019

【可以看出程序是顺序执行的,和system() 方式一样,区别就是system()不能获取子程序打印输出】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值