使用popen执行脚本并获取返回值

本文介绍了一个C语言程序实例,通过popen函数执行shell脚本并获取其返回状态码的过程。程序中利用snprintf构造命令字符串,通过popen调用执行,并读取输出以解析返回的状态值。

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

popen函数

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUF_SIZE 8192
#define RETURNED_VALUE "__returned_value_"

int
main(void)
{
	char *cmd1 = "./test.sh";

	char cmd[BUF_SIZE];
	memset(cmd, 0, sizeof(cmd));
	int ret = snprintf(cmd, sizeof(cmd), "%s 2>&1; echo %s$?", cmd1, RETURNED_VALUE);
	if (ret < 0) {
		perror("snprintf()");
		return -1;
	}
	printf("cmd: %s\n", cmd);

	FILE *fp = popen(cmd, "r");
	if (NULL == fp) {
		perror("popen()");
		return -2;
	}

	char buf[BUF_SIZE] = {[0 ... BUF_SIZE-1] = 0,};
	ssize_t buf_len = BUF_SIZE - 1;
	char *p = NULL;
	int rval = -1;
	char *line = NULL;
	size_t len = 0;
	ssize_t read = 0;

	while ((read = getline(&line, &len, fp)) != -1) {
		if (NULL != (p = strstr(line, RETURNED_VALUE))) {
			p += strlen(RETURNED_VALUE);
			rval = atoi(p);
		} else {
			if (buf_len > 0) {
				strncat(buf, line, buf_len);
				buf_len -= read;
			}
		}
	}

	printf("buf: %s", buf);
	printf("rval: %d\n", rval);

	free(line);
	pclose(fp);

	return 0;
}

脚本

#!/bin/bash

echo asdfghjkl

exit 123


 

 


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值