从Ubuntu中的另一个C文件中运行C文件

时间:2014-04-14 13:03:50

标签: c linux file posix

我需要在Ubuntu上的另一个C程序中运行一个C程序。就像是 scanf i //输入i = 2

switch (i){
case 1: print xyz;
break;
case 2: cc abc.c -lpthread (and then) ./a.out //execute this command to execute file with name abc
break;
}

怎么做?我彻底搜索了谷歌,但无法找到合适的答案。


编辑:我现在正在从bash文件运行所述执行命令。它可以轻松地解决我的需求:D

#! /bin/bash
read a
if [ $a -eq 1 ]
then
    cc ex.c -lpthread
    ./a.out
else 
    echo "hi"
fi

3 个答案:

答案 0 :(得分:4)

你需要利用fork() and exec()来产生一个子进程(无论该进程正在做什么 - 我注意到你正在编译并运行一个新进程)。

如果您想要生成一个进程并等待它,只需依靠返回(错误)代码来确定成功,那么system()就是一个选项。

答案 1 :(得分:2)

您可以运行 system 函数进行编译, fork 一个新进程, exec 执行可执行文件。

答案 2 :(得分:2)

如果你想处理父C程序中衍生孩子的一些输出,也可以填写三大选项:popen

如果你正在运行具有尽可能多的潜在输出的东西,那么编译器fork & exec可能不可避免地会在你最终的位置。