Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace system() with non-blocking function

Tags:

c

I don't want to use system() in my C program, because system(3) blocks and this is not what I want. What is the optimal way to do it?

like image 201
cateof Avatar asked Oct 01 '10 11:10

cateof


People also ask

Is select () blocking?

By using the select() call, you do not issue a blocking call until you know that the call cannot block. The select() call can itself be blocking, nonblocking, or, for the macro API, asynchronous.

Is listen () a blocking call?

listen() is non-blocking.

What is non-blocking in C?

A nonblocking send start call initiates the send operation, but does not complete it. The send start call can return before the message was copied out of the send buffer. A separate send complete call is needed to complete the communication, i.e., to verify that the data has been copied out of the send buffer.

How do I create a nonblocking socket in C++?

To mark a socket as non-blocking, we use the fcntl system call. Here's an example: int flags = guard(fcntl(socket_fd, F_GETFL), "could not get file flags"); guard(fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK), "could not set file flags"); Here's a complete example.


3 Answers

I think that a quick and dirty action is to call sytem(command &). the & will spawn the new process.

like image 126
cateof Avatar answered Sep 21 '22 23:09

cateof


Use fork() to create a new process and then use system() (or any exec function) in it. The original process will then be able to continue executing.

like image 33
abyx Avatar answered Sep 23 '22 23:09

abyx


The answer depends on what your real goal is. You don't say what platform you're on, and I know very little about Windows, so this only covers your options on linux/unix.

  1. You just want to spawn another program, and don't need to interact with it. In this case, call fork(), and then in the child process run execve() (or related function).

  2. You want to interact with another program. In this case, use popen().

  3. You want part of your program to run as a subprocess. In this case, use fork(), and call whatever functions you need to run in the child.

  4. You need to interact with part of your program running as a subprocess. Call pipe() so you have a file descriptor to communicate through, then call fork() and use the file descriptor pair to communicate. Alternatively, you could communicate through a socket, message queue, shared memory, etc.

like image 33
bstpierre Avatar answered Sep 22 '22 23:09

bstpierre