C-Menu 0.2.9
A User Interface Toolkit
Loading...
Searching...
No Matches
detach.c
Go to the documentation of this file.
1/** @file detach.c
2 @brief Launch executable, detaching from current process
3 @author Bill Waller
4 Copyright (c) 2025
5 MIT License
6 billxwaller@gmail.com
7 @date 2026-02-09
8 */
9
10#include <errno.h>
11#include <fcntl.h>
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15#include <sys/types.h>
16#include <sys/wait.h>
17#include <unistd.h>
18
19int fork_detach_execvp(char **eargv);
20
21/** @brief Fork, set new session ID, close files, and execute detached command
22 @ingroup exec
23 @param eargv - array of arguments for the command to execute
24 @return EXIT_SUCCESS on success, EXIT_FAILURE on failure
25 @details Sets the new session ID. Redirects standard file descriptors
26 to /dev/null. Closes all open file descriptors. Executes the command using
27 execvp. Exits with failure if any step fails.
28 @note Tested 2026-06-05 on Linux - appears to be functioning properly */
29int fork_detach_execvp(char **eargv) {
30 pid_t pid = fork();
31
32 if (pid < 0) {
33 fprintf(stderr, "First fork failed: %s\n", strerror(errno));
34 exit(EXIT_FAILURE);
35 }
36 if (pid == 0) {
37 if (setsid() < 0) {
38 fprintf(stderr, "Set session ID failed: %s\n", strerror(errno));
39 exit(EXIT_FAILURE);
40 }
41 close(STDIN_FILENO);
42 close(STDOUT_FILENO);
43 close(STDERR_FILENO);
44 int dev_null = open("/dev/null", O_RDWR);
45 if (dev_null != -1) {
46 dup2(dev_null, STDIN_FILENO);
47 dup2(dev_null, STDOUT_FILENO);
48 dup2(dev_null, STDERR_FILENO);
49 if (dev_null > 2) {
50 close(dev_null);
51 }
52 }
53 long max_fd = sysconf(_SC_OPEN_MAX);
54 for (long fd = 3; fd < max_fd; fd++)
55 close(fd);
56 execvp(eargv[0], eargv);
57 perror("execvp failed");
58 exit(EXIT_FAILURE);
59 }
60 return 0;
61}
62
63int main(int argc, char *argv[]) {
64 char **eargv = &argv[1];
65
66 if (argc < 2) {
67 fprintf(stderr, "Usage: %s <command> [args...]\n", argv[0]);
68 return EXIT_FAILURE;
69 }
70
71 if (fork_detach_execvp(eargv) != 0) {
72 fprintf(stderr, "Failed to fork and execute command\n");
73 return EXIT_FAILURE;
74 }
75 return EXIT_SUCCESS;
76}
int main(int argc, char **argv)
Definition amort.c:30
int fork_detach_execvp(char **)
Fork, set new session ID, close files, and execute detached command.
Definition detach.c:29