0

I need to run a C program from within another C program on Ubuntu. Something like scanf i //say i=2 is entered

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;
}

How to do that? I searched Google thoroughly but couldn't find suitable answers.


Edit: I am now running the said execute command from a bash file. It works and solves my requirement in an easy way :D

#! /bin/bash
read a
if [ $a -eq 1 ]
then
    cc ex.c -lpthread
    ./a.out
else 
    echo "hi"
fi
5
  • 5
    You say you want to run a c program, but the example you show is talking aboutcompiling a c program. Which is it? Commented Apr 14, 2014 at 13:05
  • hi..sorry..i need to compile and then run also..edited..@OliverMatthews Commented Apr 14, 2014 at 13:06
  • You can also do a system call. Lets you interact with the shell, so you could compile and run the program, or anything else you want to do on the shell. It is synchronous, however, which means that your program will not continue execution until the shell commands complete. If you want to continue while the sub-program runs, you will need fork as mentioned elsewhere. Commented Apr 14, 2014 at 13:07
  • A "c file" isn't run. It might be compiled and linked producing an executable, which in turn can be "run". Commented Apr 14, 2014 at 13:09
  • Note that you should probably only try running the program if the compilation succeeds. You can add && after the compilation command line; that will then only run ./a.out if the compiler succeeds: cc ex.c -lpthread && ./a.out (can all be on one line given that it is so short). Commented May 2, 2014 at 18:43

3 Answers 3

4

You need to make use of fork() and exec() to spawn off a subprocess (regardless of what that process is doing - I note you're compiling and running a new process).

If you want to spawn off a process and wait for it, simply relying on the return (error) code to determine success, then system() is an option.

Sign up to request clarification or add additional context in comments.

2 Comments

@osgx - of course! Now edited to reflect that possibility too. Thx
System() does run a shell.
2

You can run the system function to do the compilation and fork a new process and exec the executable.

Comments

2

Might as well fill out the Big Three Options: popen if you want to process some of the output from your spawned child in the parent C program.

If you are running something with as many potential outputs as a compiler fork & exec are probably inevitably where you will end up.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.