1

I would like to, in C code, create more than one terminal processes. As in, I want to run foo in a terminal process, and then in a separate terminal process, I want to run bar. Is this possible? Could I do it with system(char *)?

Mohit Deshpande
  • 53,877
  • 76
  • 193
  • 251

3 Answers3

2

This sounds like a job for posix_spawn(). Here is an example. Definitely do not call system() to launch new processes.

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
  • Hmm. What's wrong with `system()`? Do you recommend not using it merely because its execution is synchronous, which is probably not what the OP wants for this specific use case? Can you clarify your answer? – Lightness Races in Orbit Apr 21 '11 at 13:54
  • @Tomalak Correct, `system()` blocks and the OP wants more than one process, presumably at the same time. Also, `system()` goes through the shell, which most users don't want to do in reality. Here's a good [list of other issues with it](http://stackoverflow.com/questions/4622693/beginner-question-issuing-system-commands-in-linux-from-c-c/4622772#4622772). – chrisaycock Apr 21 '11 at 14:03
0

It's not clear what you mean by "terminal process". You can't (easily?) create another process that somehow causes the user to have more terminals open, but you can use fork(2) to create a child process.

fork creates another copy of your process with the same initial state, except that it returns 0 in the child process, and returns some non-zero PID in the parent process. So a sketch would look like:

if (fork())
    system("bar");
else
    system("foo");

This causes your original program to spawn two processes, running foo and bar.

amalloy
  • 89,153
  • 8
  • 140
  • 205
  • `fork()` returns a strictly positive integer in the parent process (namely the child's PID) and 0 in the child process, or -1 on error. Hence, `switch(pid = fork()) {/*case -1 / 0 / default*/}` is more suitable. – Philip Apr 12 '11 at 05:41
0

If you really want to be evil, assuming you are running X, you could launch xterm's like this:

while(processes to spawn)
{
    if(!fork())
        execlp("xterm", "-e", "foo"); // or "bar" or "baz" ...
}
Dave Rager
  • 8,002
  • 3
  • 33
  • 52