Files
fastfetch/src/common/processing_linux.c
T

86 lines
2.0 KiB
C
Raw Normal View History

2021-04-18 15:19:21 +02:00
#include "fastfetch.h"
#include "common/processing.h"
#include "common/io/io.h"
2023-07-10 16:14:04 +08:00
#include "common/time.h"
2021-04-18 15:19:21 +02:00
2022-06-18 14:25:31 +02:00
#include <stdlib.h>
2021-04-18 15:19:21 +02:00
#include <unistd.h>
2023-07-10 16:14:04 +08:00
#include <signal.h>
#include <poll.h>
2023-07-11 20:28:59 +08:00
#include <fcntl.h>
#include <errno.h>
2023-07-15 08:25:57 +08:00
#include <sys/wait.h>
2023-07-11 20:28:59 +08:00
enum { FF_PIPE_BUFSIZ = 4096 };
2021-04-18 15:19:21 +02:00
static inline void waitpid_wrapper(pid_t* pid)
{
// remove zombie processes
if (*pid > 0)
waitpid(*pid, NULL, 0);
}
2023-07-10 21:02:13 +08:00
const char* ffProcessAppendOutput(FFstrbuf* buffer, char* const argv[], bool useStdErr)
{
int pipes[2];
if(pipe(pipes) == -1)
return "pipe() failed";
__attribute__((__cleanup__(waitpid_wrapper))) pid_t childPid = fork();
if(childPid == -1)
return "fork() failed";
//Child
if(childPid == 0)
{
2023-07-10 21:02:13 +08:00
dup2(pipes[1], useStdErr ? STDERR_FILENO : STDOUT_FILENO);
close(pipes[0]);
close(pipes[1]);
2023-07-10 21:02:13 +08:00
close(useStdErr ? STDOUT_FILENO : STDERR_FILENO);
execvp(argv[0], argv);
exit(901);
}
//Parent
close(pipes[1]);
int FF_AUTO_CLOSE_FD childPipeFd = pipes[0];
2023-07-11 20:28:59 +08:00
int timeout = instance.config.processingTimeout;
if (timeout >= 0)
fcntl(childPipeFd, F_SETFL, fcntl(childPipeFd, F_GETFL) | O_NONBLOCK);
do
{
2023-07-11 20:28:59 +08:00
if (timeout >= 0)
{
2023-07-11 20:28:59 +08:00
struct pollfd pollfd = { childPipeFd, POLLIN, 0 };
if (poll(&pollfd, 1, timeout) == 0)
{
kill(childPid, SIGTERM);
return "poll(&pollfd, 1, timeout) timeout";
}
else if (pollfd.revents & POLLERR)
{
kill(childPid, SIGTERM);
return "poll(&pollfd, 1, timeout) error";
}
}
2023-07-11 20:28:59 +08:00
char str[FF_PIPE_BUFSIZ];
while (true)
{
2023-07-11 20:28:59 +08:00
ssize_t nRead = read(childPipeFd, str, FF_PIPE_BUFSIZ);
if (nRead > 0)
ffStrbufAppendNS(buffer, (uint32_t) nRead, str);
else if (nRead == 0)
return NULL;
else if (nRead < 0)
break;
}
2023-07-11 20:28:59 +08:00
} while (errno == EAGAIN);
return NULL;
}