Skip to content

Instantly share code, notes, and snippets.

@taviso
Last active July 29, 2022 01:56
Show Gist options
  • Save taviso/d7c2a3cb1896584f176e16fae3d59c64 to your computer and use it in GitHub Desktop.
Save taviso/d7c2a3cb1896584f176e16fae3d59c64 to your computer and use it in GitHub Desktop.
recycle PID
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <err.h>
#include <sys/types.h>
#include <sys/wait.h>
bool check_process_exists(pid_t process)
{
return !(kill(process, 0) == -1 && errno == ESRCH);
}
int main(int argc, char **argv)
{
int newpid;
int reqpid;
int status;
// Check parameters
if (argc < 3) {
errx(EXIT_FAILURE, "usage: %s <pid> <comand> [<params>...]", *argv);
}
// The process we're supposed to become
reqpid = atoi(argv[1]);
// Verify that pid is available
if (check_process_exists(reqpid)) {
errx(EXIT_FAILURE, "the requested pid already exists");
}
do {
if ((newpid = fork()) == 0) {
if (getpid() == reqpid) {
execvp(argv[2], &argv[2]);
}
exit(1);
}
if (newpid < 0) {
err(EXIT_FAILURE, "fork failed");
}
if (waitpid(newpid, &status, 0) != newpid) {
err(EXIT_FAILURE, "unexpected waitpid result");
}
} while (newpid != reqpid);
if (WIFEXITED(status)) {
return WEXITSTATUS(status);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment