Use switch with fork()

Allows dropping a local variable if the explicit PID is not needed
and it makes it clearer what happens.
Also, one should always strive for consistency for cases like these.
This commit is contained in:
FRIGN 2015-03-09 15:01:29 +01:00
parent 6f207dac5f
commit a8bd21c0ab
3 changed files with 11 additions and 14 deletions

10
cron.c
View File

@ -102,20 +102,20 @@ runjob(char *cmd)
} }
} }
pid = fork(); switch ((pid = fork())) {
if (pid < 0) { case -1:
logerr("error: failed to fork job: %s time: %s", logerr("error: failed to fork job: %s time: %s",
cmd, ctime(&t)); cmd, ctime(&t));
return; return;
} else if (pid == 0) { case 0:
setsid(); setsid();
loginfo("run: %s pid: %d at %s", loginfo("run: %s pid: %d at %s",
cmd, getpid(), ctime(&t)); cmd, getpid(), ctime(&t));
execl("/bin/sh", "/bin/sh", "-c", cmd, (char *)NULL); execl("/bin/sh", "/bin/sh", "-c", cmd, (char *)NULL);
logerr("error: failed to execute job: %s time: %s", logwarn("error: failed to execute job: %s time: %s",
cmd, ctime(&t)); cmd, ctime(&t));
_exit(1); _exit(1);
} else { default:
je = emalloc(sizeof(*je)); je = emalloc(sizeof(*je));
je->cmd = estrdup(cmd); je->cmd = estrdup(cmd);
je->pid = pid; je->pid = pid;

7
tar.c
View File

@ -47,17 +47,16 @@ static char filtermode;
static FILE * static FILE *
decomp(FILE *fp) decomp(FILE *fp)
{ {
pid_t pid;
int fds[2]; int fds[2];
if (pipe(fds) < 0) if (pipe(fds) < 0)
eprintf("pipe:"); eprintf("pipe:");
pid = fork(); switch (fork()) {
if (pid < 0) { case -1:
weprintf("fork:"); weprintf("fork:");
_exit(1); _exit(1);
} else if (!pid) { case 0:
dup2(fileno(fp), 0); dup2(fileno(fp), 0);
dup2(fds[1], 1); dup2(fds[1], 1);
close(fds[0]); close(fds[0]);

View File

@ -164,15 +164,13 @@ waitchld(void)
static void static void
spawn(void) spawn(void)
{ {
pid_t pid;
int savederrno; int savederrno;
pid = fork(); switch (fork()) {
if (pid < 0) { case -1:
weprintf("fork:"); weprintf("fork:");
_exit(1); _exit(1);
} case 0:
if (pid == 0) {
execvp(*cmd, cmd); execvp(*cmd, cmd);
savederrno = errno; savederrno = errno;
weprintf("execvp %s:", *cmd); weprintf("execvp %s:", *cmd);