程序和shell脚本交互方法

来源:互联网 发布:吴昕开的淘宝店叫什么 编辑:程序博客网 时间:2024/06/01 08:41

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/bashecho "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]# ./teststate_1;1024;;The first!state_2;2048;The sencond!state_3;3096;The third!start:1454376977 ;end:1454376979[root@localhost test]#

脚本按照一定格式输出,c程序按照该格式进行解析,即可得到脚本的相应执行结果。

0 0
原创粉丝点击