Not exactly a script, but I wrote a utility for launching programs into the background. It's most useful for starting a GUI from a terminal window when you don't want to see the logs, and I do this pretty often.
#define _GNU_SOURCE
#include <spawn.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
extern char **environ;
int
main(int argc, char **argv) {
if (argc < 2) {
printf("usage: %s <program> [args]\n", argv[0]);
return 1;
}
if (-1 == close_range(3, -1, 0)) {
perror("close_range");
return 1;
}
posix_spawnattr_t attr;
if (posix_spawnattr_init(&attr)) {
perror("posix_spawnattr_init");
return 1;
}
posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSID);
posix_spawn_file_actions_t acts;
if (posix_spawn_file_actions_init(&acts)) {
perror("posix_spawn_file_actions_init");
return 1;
}
posix_spawn_file_actions_addopen(&acts, 0, "/dev/null", O_RDONLY, 0);
posix_spawn_file_actions_addopen(&acts, 1, "/dev/null", O_WRONLY, 0);
posix_spawn_file_actions_addopen(&acts, 2, "/dev/null", O_WRONLY, 0);
pid_t pid;
int err = posix_spawnp(&pid, argv[1], &acts, &attr, &argv[1], environ);
if (err) {
printf("failed to spawn process: %s\n", strerror(err));
return 1;
}
return 0;
}