Starting background process

I have a console application that I need to do some checking of its command line arguments, I then need it to print some output and if everything is ok, fork into the background. I need this same behaviour in both Windows and Linux.

I know a lot of people argue against system, but what are the negatives of the following solution and how can I deal with them?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void launchBackground(int argc, char **argv) {
  std::ostringstream oss;
  for(int i=1;i!=argc;++i) oss << argv[i] << " ";
  oss << "launchbg ";
  std::string cmd;
#ifdef _WIN32
  cmd = "start c:\full\path\to\program.exe " + oss.str();
#else
  cmd = "/full/path/to/program " + oss.str() + " &";
#endif
  system(cmd);
}

int main(int argc, char **argv) {
  if(argv[argc-1] == std::string("launchbg")) {
    doRealWork(argc, argv);
  } else {
    if(checkArguments(argc, argv)) {
      std::cout << "ok" << std::endl;
      launchBackground(argc, argv);
    } else {
      std::cout << "Problem with arguments" << std::endl;
    }
  }
  return 0;
}
In windows the best way is to use CreateProcess() API. (or exec family of functions implemented in CRT if you want to be cross-platform).
or exec family of functions implemented in CRT if you want to be cross-platform


Could you clarify for me how I can use these functions to get rid of my controlling terminal. I thought exec would just replace the current foreground process with another foreground process. I want a background process.

In Linux I would fork, return from the parent and exec in the child. But I don't believe Windows has a fork.
No, windows does not have fork().
I never use exec in windows anyway, but CreateProcess() can start a background process for sure (with or without waiting to end).
Last edited on
Topic archived. No new replies allowed.