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

popen函数

 

 

#include 
#include 
#include 

#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


 

 


 

你可能感兴趣的:(Linux小程序)