1515#define MIMETYPE_JSON " application/json; charset=utf-8"
1616
1717// auto generated files (see README.md for details)
18- #include " index.html.gz.hpp "
19- #include " loading.html.hpp "
18+ #include < signal.h >
19+ #include < unistd.h >
2020
2121#include < atomic>
2222#include < chrono>
23+ #include < cinttypes>
2324#include < condition_variable>
2425#include < cstddef>
25- #include < cinttypes>
2626#include < deque>
2727#include < memory>
2828#include < mutex>
29- #include < signal.h>
3029#include < thread>
3130#include < unordered_map>
3231#include < unordered_set>
3332
33+ #include " index.html.gz.hpp"
34+ #include " loading.html.hpp"
35+
36+ #ifdef _WIN32
37+ #include < process.h>
38+ #define getpid _getpid
39+ #endif
40+
3441using json = nlohmann::ordered_json;
3542
3643constexpr int HTTP_POLLING_SECONDS = 1 ;
@@ -3691,6 +3698,68 @@ inline void signal_handler(int signal) {
36913698 shutdown_handler (signal);
36923699}
36933700
3701+ static bool check_pid_alive (const pid_t pid) {
3702+ return pid > 0 && !kill (pid, 0 );
3703+ }
3704+
3705+ class PidFile {
3706+ public:
3707+ FILE * file = nullptr ;
3708+ std::string fname;
3709+ bool rm = false ;
3710+
3711+ FILE * open (const std::string & filename, const char * mode, const bool r = false ) {
3712+ file = ggml_fopen (filename.c_str (), mode);
3713+ fname = filename;
3714+ rm = r;
3715+
3716+ return file;
3717+ }
3718+
3719+ void close () {
3720+ fclose (file);
3721+ file = nullptr ;
3722+
3723+ if (rm) {
3724+ // Remove stale pidfil
3725+ unlink (fname.c_str ());
3726+ }
3727+ }
3728+
3729+ ~PidFile () {
3730+ if (file) {
3731+ close ();
3732+ }
3733+ }
3734+ };
3735+
3736+ static bool is_old_pid_alive (const std::string & filename) {
3737+ pid_t oldpid = 0 ;
3738+ PidFile f;
3739+ if (f.open (filename, " r" )) {
3740+ if (fscanf (f.file , " %d" , &oldpid) == 1 ) {
3741+ if (check_pid_alive (oldpid)) {
3742+ LOG_ERR (" Process already running with PID %d\n " , oldpid);
3743+ return true ;
3744+ }
3745+ }
3746+ }
3747+
3748+ return false ;
3749+ }
3750+
3751+ static int create_pidfile (const std::string & pidfile, PidFile & f) {
3752+ if (!f.open (pidfile.c_str (), " w" , true )) {
3753+ LOG_ERR (" Unable to open pidfile %s: %s\n " , pidfile.c_str (), strerror (errno));
3754+ return -1 ;
3755+ }
3756+
3757+ fprintf (f.file , " %d\n " , getpid ());
3758+ fflush (f.file );
3759+
3760+ return 0 ;
3761+ }
3762+
36943763int main (int argc, char ** argv) {
36953764 // own arguments required by this example
36963765 common_params params;
@@ -3699,6 +3768,13 @@ int main(int argc, char ** argv) {
36993768 return 1 ;
37003769 }
37013770
3771+ PidFile f;
3772+ if (!params.pidfile .empty ()) {
3773+ if (is_old_pid_alive (params.pidfile ) || create_pidfile (params.pidfile , f)) {
3774+ return 1 ;
3775+ }
3776+ }
3777+
37023778 common_init ();
37033779
37043780 // struct that contains llama context and inference
0 commit comments