【问题标题】:Run c program from another one using system gcc command使用系统 gcc 命令从另一个运行 c 程序
【发布时间】:2021-11-24 10:46:28
【问题描述】:

我正在尝试使用 c 中的系统从我的程序中运行特定的 c 程序。 gcc 告诉我“没有这样的文件或目录”,即使我把文件 在另一个程序目录中。目的是在第一个程序中达到某些条件时执行第二个程序。有什么帮助吗?

if(a==0){
 system(" gcc -g -o iptablesExample mainiptables.c  -lip4tc -lip6tc -ldl ");
                       system(" ./iptablesExample");
}

【问题讨论】:

  • iptablesExample的编译成功了吗?你能在进程的当前目录中找到它吗?在尝试执行之前添加system("ls"); 以查看当前目录中的文件。
  • 是的,在shell中编译成功,文件不在正确的目录中!
  • 您没有检查第一个system 命令的返回值(它应该为零)。如果你得到一个零,输出文件肯定存在。

标签: c shell gcc command system


【解决方案1】:

也许你可以用 execve 和 fork 试试你的命令,但我不确定它是否有效

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>


int main(int ac, char **av, char **env) {
  pid_t pid = fork();
  char *args[] = {"/usr/bin/ls", "-la", NULL}; //put the absolute path of gcc

  if (pid == 0)
  {
    if (execve(args[0], args, env) == -1)
       perror("error");
  }
  wait(&pid);
  return 0;
}

一定要放绝对路径

【讨论】:

  • tks。有什么例子吗?
  • 如果它不适用于system,它不会通过切换到forkexecve 来开始工作。
  • 你有一个例子,希望它能起作用!
  • @lilie82 我编辑了答案,如果它不起作用,请告诉我错误的消息
猜你喜欢
  • 1970-01-01
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
相关资源
最近更新 更多