I am writing width-memory and performance-sensitive multithread server. Therefore, I need the alternative for standard system()
and popen()
calls that does not use fork()
that clone all process memory that usually takes too much time.
Seems, need to use vfork()
then execve()
to made it.
Can somebody help me with two functions:
system()
call. Example of behavior: one thread call the function to execute eg touch filename
and called thread waiting until execution end. (all other threads must continue working)popen()
call Example of behavior: the same behavior, but need to get output of command eg ls -flags
(alternative for this code: Correct Code - Non-blocking pipe with popen )thanks
This is just a suggestion for how to approach your proposed solution. For the two specific actions you are asking about:
touch
: you can achieve a similar effect by opening and closing the file you want to touch
O_TRUNC
flag on open
ls
: it is a little more painful, because you will need to use dirent.h
on POSIX systems, and walk the results of
opendir
readdir
closedir
when you are doneIf you want to replace the system
and popen
calls with something equivalent using vfork
, there is some care involved. The vfork
call is a little tricky to use, because if the child does anything other than exec
right after the call, you take the chance of corrupting the memory state of the parent.
For your replacement to system
:
system
on the provided argument, or parse the command string and call exec
system
replacement function, create an arg vector to call the helper program and passing in the program string you really want executed in as an argument to this programvfork
, you immediately exec
the helper program in the childIn your popen
replacement:
stdout
and stdin
file descriptors as arguments, and the string of the command you want to execute
0
or 1
(or both) as indicated by the argumentspopen
and proxy data between parent and child, or call exec
after parsing the command stringpopen
replacement function, use pipe
to create the stdout
or stdin
communication channel (as per the second popen
function parameter) and create an arg vector to call the helper program, passing in the appropriate file descriptor number and command string as argumentsvfork
, you immediate exec
the helper program in the childpclose
replacement to reap the child process