cool_autostart.c (1350B)
1 /* dwm will keep pid's of processes from autostart array and kill them at quit */ 2 static pid_t *autostart_pids; 3 static size_t autostart_len; 4 5 /* execute command from autostart array */ 6 static void 7 autostart_exec() 8 { 9 const char *const *p; 10 struct sigaction sa; 11 size_t i = 0; 12 13 /* count entries */ 14 for (p = autostart; *p; autostart_len++, p++) 15 while (*++p); 16 17 autostart_pids = malloc(autostart_len * sizeof(pid_t)); 18 for (p = autostart; *p; i++, p++) { 19 /* kill any existing instance before starting a new one (seamless restart) */ 20 FILE *cmd; 21 char pidline[256]; 22 pid_t oldpid; 23 int len = snprintf(pidline, sizeof(pidline), "pidof -s %s", *p); 24 if (len > 0 && (size_t)len < sizeof(pidline) && (cmd = popen(pidline, "r"))) { 25 if (fgets(pidline, sizeof(pidline), cmd)) { 26 oldpid = (pid_t)atol(pidline); 27 if (oldpid > 0) { 28 kill(oldpid, SIGTERM); 29 waitpid(oldpid, NULL, WNOHANG); 30 } 31 } 32 pclose(cmd); 33 } 34 35 if ((autostart_pids[i] = fork()) == 0) { 36 setsid(); 37 38 /* Restore SIGCHLD sighandler to default before spawning a program */ 39 sigemptyset(&sa.sa_mask); 40 sa.sa_flags = 0; 41 sa.sa_handler = SIG_DFL; 42 sigaction(SIGCHLD, &sa, NULL); 43 44 execvp(*p, (char *const *)p); 45 fprintf(stderr, "dwm: execvp %s\n", *p); 46 perror(" failed"); 47 _exit(EXIT_FAILURE); 48 } 49 /* skip arguments */ 50 while (*++p); 51 } 52 } 53