您的位置:首页 > 运维架构 > Shell

程序和shell脚本交互方法

2016-02-02 09:41 661 查看
c程序和shell脚本交互方法可使用popen()+fget()方式进行。

举例如下:

c程序

test.c:

#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(int argc ,char *argv[])
{
char cmd[512]={0};
snprintf(cmd,sizeof(cmd),"/root/test/test.sh",
argv[1],argv[2],argv[3],argv[4]);
FILE *fp = popen(cmd,"r");
if(fp ==NULL)
return 0;

char *ptr=NULL;
char *ptr1=NULL;
char line[512]={0};
char status[512]={0};
int state=0;
time_t start=0, end=0;
long long  total=0, cur=0;

start=time(NULL);
while(fgets(line,sizeof(line),fp))
{
state=strtol(line,&ptr,10);
if(state == LONG_MAX || state == LONG_MIN || ptr == line)
{
printf("%s\n",line);
continue;
}

total=strtoll(&ptr[1],&ptr1,10);
strncpy(status,&ptr1[1],sizeof(status));

printf("state:%u\n",state);
printf("total:%llu\n",total);
printf("status:%s\n",status);
}
pclose(fp);
fp = NULL;
end=time(NULL);
printf("start:%lu ;end:%lu\n",start,end);
return 0;
}


shell脚本

test.sh:

#!/bin/bash
echo "state_1;1024;;The first!"
sleep 1
echo "state_2;2048;The sencond!"
sleep 1
echo "state_3;3096;The third!"
exit 0


编译程序并执行

[root@localhost test]# gcc test.c -o test
[root@localhost test]# ./test
state_1;1024;;The first!

state_2;2048;The sencond!

state_3;3096;The third!

start:1454376977 ;end:1454376979
[root@localhost test]#


脚本按照一定格式输出,c程序按照该格式进行解析,即可得到脚本的相应执行结果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: