linux C代码调用shell命令方法

摘抄:https://blog.csdn.net/u010299133/article/details/85637263
主要有三种方法:exec函数簇,system函数以及popen函数,其中需要注意的是,exec函数簇的函数执行成功后是无返回的,一般需要和fork()函数同时使用。在使用时需要另外的fork一个进程。 popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。

exec函数簇:
函数原型:

#include <unistd.h>
 
extern char **environ;
 
int execl(const char *path, const char *arg, ...
                       /* (char  *) NULL */);
int execlp(const char *file, const char *arg, ...
                       /* (char  *) NULL */);
int execle(const char *path, const char *arg, ...
                       /*, (char *) NULL, char * const envp[] */);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],
                       char *const envp[]);
使用如下: 

  7     char *const argv[] = {"ls", "-al", "NULL"};
  8     char *const envp[] = {"PATH=/bin:/usr/bin", NULL};
  9     
 10     execl("/bin/ls", "ls", "-al", (char*)NULL);
 11     
 12     execv("/bin/ls", argv);
 13     
 14     execle("/bin/ls", "ls", "-al", (char*)NULL, envp);
 15     
 16     execve("/bin/ls", argv, envp);
 17     
 18     execlp("ls", "ls", "-al", (char*)NULL);
 19     
 20     execvp("ls", argv);

system函数:
函数原型:

#include <stdlib.h>

int system(const char *command);
直接将需要执行的命令或者shell脚本放入其中即可:如,

system("/etc/xxx.sh");
system("ls -al /etc/");

popen函数:
FILE * popen ( const char * command , const char * type );

int pclose ( FILE * stream );
如:

#include<stdio.h>
#define _LINE_LENGTH 300
int main(void) 
{
    FILE *file;
    char line[_LINE_LENGTH];
    file = popen("ls", "r");
    if (NULL != file)
    {
        while (fgets(line, _LINE_LENGTH, file) != NULL)
        {
            printf("line=%s\n", line);
        }
    }
    else
    {
        return 1;
    }
    pclose(file);
    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值