Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-blocking version of system()

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.

like image 886
Simon Hodgson Avatar asked Jun 16 '09 16:06

Simon Hodgson


People also ask

Is system a blocking call?

There are system call which provides asynchronous IO and they are non-blocking. Note that there is still a context switch that happens here, only the application has to take care of the asynchronous nature of the call.

What is non-blocking programming?

Non-Blocking This term is mostly used with IO. What this means is that when you make a system call, it will return immediately with whatever result it has without putting your thread to sleep (with high probability).

What is blocking function?

A function that stops script execution until it ends. For example, if I had a function in my language that was used to write to a file, like so: fwrite(file, "Contents"); print("Wrote to file!"); The print statement would only be executed once the file has been written to the disk.

Does std :: system Block?

std::system will block until the command is finished, so yes, the espresso. out file will be "ready" by the time you try to open it.


3 Answers

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.

like image 157
Doug T. Avatar answered Sep 27 '22 22:09

Doug T.


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...
like image 26
FreeMemory Avatar answered Sep 27 '22 22:09

FreeMemory


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

like image 23
Martin Beckett Avatar answered Sep 27 '22 21:09

Martin Beckett