-
Notifications
You must be signed in to change notification settings - Fork 0
/
launchbg.c
40 lines (31 loc) · 1.02 KB
/
launchbg.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s command [arg1 arg2 ...]\n", argv[0]);
return 1;
}
// Concatenate all the arguments into a single string
char command[1024] = "";
for (int i = 1; i < argc; i++) {
strcat(command, argv[i]);
strcat(command, " ");
}
pid_t pid = fork(); // Create a child process
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
return 1;
}
if (pid == 0) { // This block will be executed by the child process
char *args[] = {"/bin/bash", "-c", command, NULL};
execvp(args[0], args); // Replace the current process image with a new one
// If execvp returns, it must have failed.
fprintf(stderr, "Exec failed\n");
return 1;
}
// The parent process continues execution here.
// printf("Started the command in the background, PID = %d\n", pid);
return 0;
}