Skip to content

Commit 30704d2

Browse files
committed
librc: fix unnecessary copying parent memory page table
posix_spawn() is a more lightweight and modern alternative to fork()/exec(), which are used inside popen(). The main advantage of posix_spawn is that it can create a new process without completely duplicating the address space of the parent process. References: - https://blog.famzah.net/2018/12/19/posix_spawn-performance-benchmarks-and-usage-examples/ - https://lobste.rs/s/smbsd5/fork_road - https://www.reddit.com/r/C_Programming/comments/1lvdhp2/fork_vs_posix_spawn/
1 parent 584444d commit 30704d2

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/librc/librc-depend.c

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
#include <sys/stat.h>
2828
#include <time.h>
2929
#include <unistd.h>
30+
#include <spawn.h>
3031

3132
#include "queue.h"
3233
#include "librc.h"
@@ -791,12 +792,27 @@ rc_deptree_update(void)
791792
bool retval = true;
792793
const char *sys = rc_sys();
793794
int serrno;
795+
pid_t pid;
796+
char *argv[] = { "sh", "-c", GENDEP, NULL };
797+
int pipe_fd[2];
794798

795799
/* Phase 1 - source all init scripts and print dependencies */
796800
setup_environment();
797-
if (!(fp = popen(GENDEP, "r")))
801+
if (pipe(pipe_fd) == -1)
798802
return false;
799803

804+
if (posix_spawnp(&pid, argv[0], NULL, NULL, argv, environ) != 0) {
805+
close(pipe_fd[0]);
806+
close(pipe_fd[1]);
807+
return false;
808+
}
809+
close(pipe_fd[1]);
810+
fp = fdopen(pipe_fd[0], "r");
811+
if (!fp) {
812+
close(pipe_fd[0]);
813+
return false;
814+
}
815+
800816
config = rc_stringlist_new();
801817

802818
deptree = make_deptree();
@@ -876,7 +892,7 @@ rc_deptree_update(void)
876892
}
877893
}
878894
free(line);
879-
pclose(fp);
895+
fclose(fp);
880896

881897
/* Phase 2 - if we're a special system, remove services that don't
882898
* work for them. This doesn't stop them from being run directly. */

0 commit comments

Comments
 (0)