Question

Does someone know how to open the terminal and execute several commands using a C program ?

I have a program in C and another sets of commands executed by the terminal. I need to combine them into one program in C.

I'm using Ubuntu 10.04.

Thanks!

Was it helpful?

Solution 2

Check "man xterm", parameter -e. Then, in C, you can:

system("xterm -e ls")

OTHER TIPS

Your question may be somewhat misleading.

Because you want to run all the terminal commands in the c-code, perhaps you actually have only textual input / output with these commands. If so, you probably do not need the terminal.


I use popen when the output of the (terminal) program is a text stream. It is probably the easiest to use. As an example:

 ...
 const char* cmndStr = "ls -lsa";
 FILE* pipe = popen(cmndStr, "r");
 ...

The popen instruction executes the command in the cmndStr, and any text written to the commands (ls -lsa) standard output, is redirected into the pipe, which is then available for your C program to read in.

popen opens a separate process (but without a terminal to work in, just the pipe)

'Fork' is another way to launch a separate process, with some control over the launched processes' std i/o, but again, I think not a terminal.


On the other hand, if your output is not a simple text stream, maybe you can get by with a output-only dedicated terminal screen to accommodate special output activity. For instance, when I work with ncurses:

I manually open a terminal in the conventional way, and in the terminal

  • issue the command "tty" to find out the device name, and

  • issue a "cd" to set the focus to the working dir.

    dmoen@C5:~$ tty

    /dev/pts/1

    dmoen@C5:~$ cd work

    dmoen@C5:~/work$

Then I start my program (in a different tty), and let the program know which device I want it to use for the special output (i.e. /dev/pts/1 ) ... I typically use command line parameters to tell my program which pts or extra terminals I want it to use, but environment variables, pipes, in/out redirection, and other choices exist.

I have not tried (lately) to launch a terminal (as suggested by smrt28), except in shell. I believe this will work, but I do not see how the output from the terminal command (ls in the example) would be delivered back to your program. popen trivially delivers a text stream.

A long time ago, I used a device called 'pty' which works like a terminal, but I don't remember how to connect it usefully.


There is a set of 'exec' commands ... see man exec. To connect them back to your program, you will probably work with files, or perhaps redirecting i/o. Too many choices to list here.


And also, maybe you can connect these commands with your c program using shell pipes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top