Alex Rivera | Logout

How do you spawn another process in C?

Asked 2008-08-19T22:53:47.130
39

How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux.

Edit
Report

3 Answers

21

If you want to perform more complicated operations, like reading the output of the external program, you may be better served by the popen system call. For example, to programmatically access a directory listing (this is a somewhat silly example, but useful as an example), you could write something like this:

#include <stdio.h>

int main()
{
  int entry = 1;
  char line[200];
  FILE* output = popen("/usr/bin/ls -1 /usr/man", "r");
  while ( fgets(line, 199, output) )
  {
    printf("%5d: %s", entry++, line);
  }
}

to give output like this

1: cat1
2: cat1b
3: cat1c
4: cat1f
5: cat1m
6: cat1s
...
answered 2008-08-20T01:52:59.040
2

One solution is the system function defined in stdlib.h

int system(const char *string);

system api example

answered 2008-08-19T22:59:56.897
1

If you need to check/read/parse the output of your external command, I would suggest to use popen() instead of system().

answered 2008-12-23T16:08:56.323

Your Answer