Skip to content

Commit

Permalink
Add fork_func.{c,h}
Browse files Browse the repository at this point in the history
  • Loading branch information
gperciva committed Jan 14, 2024
1 parent bfffdd7 commit ebfe5c8
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 0 deletions.
1 change: 1 addition & 0 deletions liball/Makefile.BSD
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ SRCS += asprintf.c
SRCS += b64encode.c
SRCS += daemonize.c
SRCS += entropy.c
SRCS += fork_func.c
SRCS += getopt.c
SRCS += hexify.c
SRCS += humansize.c
Expand Down
77 changes: 77 additions & 0 deletions util/fork_func.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#include <sys/wait.h>

#include <stdint.h>
#include <unistd.h>

#include "warnp.h"

#include "fork_func.h"

/**
* fork_func(func, cookie):
* Fork and run ${func} in a new process, with ${cookie} as the sole argument.
*/
pid_t
fork_func(int (* func)(void *), void * cookie)
{
pid_t pid;

/* Fork */
switch (pid = fork()) {
case -1:
/* Error in fork system call. */
warnp("fork");
goto err0;
case 0:
/* In child process: Run the provided function, then exit. */
_exit(func(cookie));
default:
/* In parent process: do nothing else. */
break;
}

/* Success! */
return (pid);

err0:
/* Failure! */
return (-1);
}

/**
* fork_func_wait(pid):
* Wait for the process ${pid} to finish. Print any error arising from ${pid}.
* If ${pid} exited cleanly, return its exit code; otherwise, return -1.
*/
int
fork_func_wait(pid_t pid)
{
int status;
int rc = -1;

/* Wait for the process to finish. */
if (waitpid(pid, &status, 0) == -1) {
warnp("waitpid");
goto err0;
}

/* Print the error status, if applicable. */
if (WIFEXITED(status)) {
/* Child ${pid} exited cleanly. */
rc = WEXITSTATUS(status);
} else {
/*
* Child ${pid} did not exit cleanly; warn about the reason
* for the unclean exit.
*/
if (WIFSIGNALED(status))
warn0("pid %jd: terminated with signal %d",
(intmax_t)pid, WTERMSIG(status));
else
warn0("pid %jd: exited for an unknown reason");
}

err0:
/* Done! */
return (rc);
}
19 changes: 19 additions & 0 deletions util/fork_func.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#ifndef FORK_FUNC_H_
#define FORK_FUNC_H_

#include <sys/types.h>

/**
* fork_func(func, cookie):
* Fork and run ${func} in a new process, with ${cookie} as the sole argument.
*/
pid_t fork_func(int (*)(void *), void *);

/**
* fork_func_wait(pid):
* Wait for the process ${pid} to finish. Print any error arising from ${pid}.
* If ${pid} exited cleanly, return its exit code; otherwise, return -1.
*/
int fork_func_wait(pid_t);

#endif /* !FORK_FUNC_H_ */

0 comments on commit ebfe5c8

Please sign in to comment.