C语言调用SHELL脚本

 在Linux 环境下Shell脚本具有非常强大的功能!使用Shell可以很方便的使用和管理Linux系统,最近学习了一点shell知识,所以一直在
想要是可以在C/C++中调用shell脚本那该有多好啊! 因为使用C/C++要几百行代码才能搞定的!使用shell只要短短十几行就可以轻松搞定!
            今天在看一个视频的时候!视频中给出的一个简单的C程序!
#include<stdio.h>
#include<unistd.h>

int main(void)
{
    for(int i=0; i<=100; ++i)
    {
        printf("Completed: %d%% ", i);
        fflush(stdout);
        sleep(1);
    }
    return 0;
}

此程序就是想利用fflush(stdout) 来清除缓冲区!从而使输出只有一行!但是在我的系统上去怎么也实现不了!(希望有大师指点指点!视频里的教授用的是Mac OS操作系统!)我在网上也没有找到原因!所以我只有另寻道路!
想到其就是清除掉了已输出的内容!这个就是在终端中使用clear 命令啊! 所以想到可以使用system("clear");   查看了一下system函数的手
册页! 发现这个system函数就是我所要找的可以实现在C/C++中调用shell脚本的工具!
       #include <stdlib.h>
       int system(const char *command);
DESCRIPTION
       system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed.  During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.
因为system()执行的命令为/bin/sh -c command , 也就是说在终端中可以运行的shell 命令都可以调用执行!所以

#include<stdio.h>
#include<unistd.h>

int main(void)
{
    for(int i=0; i<=100; ++i)
    {
            printf("Completed: %d%%\n", i);  // 这里“\n”是必须要加的!不然不会打印
            system("clear");
            sleep(1);
    }
    return 0;
}

虽然这个程序勉强可以满足要求!但是还是不够尽人意!所以有想了想!既然可以用一般命令!那应该也可以运行一个自己写的脚本! 于是
便动手写了个脚本 shell.sh
#!/bin/bash
#Filename: shell.sh
echo -n Completed:
tput sc

count=0;
while true; do
        if [ $count -lt 101 ];  then
                let count++;
                tput rc;
                tput ed;
                echo -n $count%
                sleep 1;
        else echo ; exit 0;
        fi
done

然后就是chmod u+x shell.sh 将shell.sh设为可执行,然后在同目录下建立fun.c
#include<stdlib.h>

int main(void)
{
    system("./shell.sh");
    return 0;
}

这样直接调用自己编写的shell脚本同样达到了目的!!!(第一次写博客!!!自己喜一个!!)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值