jondinham
jondinham

Reputation: 8511

Open a process from file, in C++ on Linux

I'm coding my application in C++ on Linux. C++ has a function called 'system' to execute a programme.

I try to open the gnome-system-monitor from C++ like this:

system("gnome-system-monitor");

However, the thread of my application blocks when I call this 'system' function until I close the window of gnome-system-monitor.

Any other ways to open a process from file without blocking the caller process?

Upvotes: 1

Views: 1129

Answers (4)

Greg Price
Greg Price

Reputation: 2989

The classic way, which works on any Linux or otherwise POSIX-based system, is

if (0 == fork()) {
  execlp("gnome-system-monitor", "gnome-system-monitor", (char *)NULL);
}

(with error handling omitted from this example.) This (a) creates a new process, (b) in that new process, runs "gnome-system-monitor" after searching the PATH environment variable to find such a command, (c) passes it the name "gnome-system-monitor" as argv[0] and no other arguments. In the parent, once the new process is created it barrels on ahead without waiting for any result.

See the man pages for fork and execlp for more details.

Upvotes: 2

Gnome is built above GTk (which contains Glib), and you probably want the Glib Spawning Processes functions.

Of course, on Linux and Unix, processes are forked. Read a good book like advanced unix programming and advanced linux programming to learn more about syscalls related to processes, notably fork(2), execve(2), pipe(2). Read also about the proc(5) filesystem.

Upvotes: 1

Adrian Herea
Adrian Herea

Reputation: 658

Yes. Call System function on a separte thread.

Upvotes: 0

arsenm
arsenm

Reputation: 2933

fork/exec or posix_spawn. glib also has GSpawn if you are using that.

Upvotes: 1

Related Questions