Non-blocking version of system()

26,976

Solution 1

One option is in your system call, do this:

 system("ls -l &");

the & at the end of the command line arguments forks the task you've launched.

Solution 2

Why not use fork() and exec(), and simply don't call waitpid()?

For example, you could do the following:

// ... your app code goes here ...
pid = fork();
if( pid < 0 )
    // error out here!
if( !pid && execvp( /* process name, args, etc. */ )
    // error in the child proc here!
// ...parent execution continues here...

Solution 3

The normal way to do it, and in fact you shouldn't really use system() anymore is popen.
This also allows you to read or write from the spawned process's stdin/out

edit: See popen2() if you need to read and write - thansk quinmars

Share:
26,976
Simon Hodgson
Author by

Simon Hodgson

Software Engineer

Updated on November 28, 2020

Comments

  • Simon Hodgson
    Simon Hodgson over 3 years

    I want to launch a process from within my c program, but I don't want to wait for that program to finish. I can launch that process OK using system() but that always waits. Does anyone know of a 'non-blocking' version that will return as soon as the process has been started?

    [Edit - Additional Requirement] When the original process has finished executing, the child process needs to keep on running.