C程序调用shell脚本共有三种方法

本文介绍了C程序调用shell脚本的三种方法:1)使用system()函数,直接传入shell脚本路径;2)利用popen()函数,通过'r'或'w'指定读写方式,创建管道与子进程通信。示例代码展示了如何实现这两种方法,并给出了对应的shell脚本内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C程序调用shell脚本共有三种方法:

1、system()   #直接放入shell脚本路径

在c_call_shell.c文件

  1#include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #include <unistd.h>
  5
  6 void c_call_shell(char *shell_path)
  7 {
  8  char str[]="/usr/sxf/MFS/4_25/test/shell.sh";
  9  system(shell_path);
 10  system(str);
 11 }
 12
 13 int main(int argc,char* argv[])
 14 {
 15  c_call_shell(argv[1]);
 16 }

shell.sh程序

 #!/bin/sh
  2 #shell.sh
  3
  4 echo "hello,world"

2、popen(char *command,char *type)  

type为r或w

command 为shell脚本路径

popen()会调用fork()产生子进程,子进程调用/bin/sh -c来执行参数command指令。参数type可使用“r”代表读,“w”代表写。

popen()会建立管道连到子进程的标准输出设备或标准输入设备,然后返回一个文件指针,所有对文件指针的操作都可以用,除了fclose()外。

c_print_shell.c 

     #include <stdio.h>
  2 int main(int argc,char *argv[])
  3 {
  4   FILE *fp=NULL;
  5   char buffer[80];
  6   fp=popen("/usr/sxf/MFS/4_25/test/shell.sh","r");
  7   fgets(buffer,sizeof(buffer),fp);
  8   printf("%s\n",buffer);
  9   pclose(fp);
 10
 11   return 0;
 12 }

shell.sh

 #!/bin/sh
  2 #shell.sh
  3
  4 echo "hello,world"


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值