Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdlib>
- #include <string>
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <sys/un.h>
- #include <signal.h>
- int childPID;
- void restartApp(int) {
- if(childPID) {
- int statval;
- kill(childPID, SIGINT);
- wait(&statval);
- printf("Restarting...\n");
- system("./rm");
- exit(0);
- } else {
- kill(getppid(), SIGUSR1);
- }
- }
- void inthandler(int) {
- printf("Stopping in 60 seconds...\n");
- sleep(60);
- printf("Shutting down\n");
- exit(0);
- }
- auto main(int argc, char ** argv) -> int {
- signal(SIGHUP, SIG_IGN);
- signal(SIGUSR1, &restartApp);
- struct stat buf;
- stat("rm", &buf);
- time_t last_mod=buf.st_mtim.tv_sec;
- int s, s2, len;
- unsigned int t;
- struct sockaddr_un local,remote;
- char str[1024];
- printf("%d: Starting server\n", getpid());
- if((childPID=fork()) == 0)
- {
- signal(SIGINT, &inthandler);
- if((s=socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
- perror("socket");
- exit(1);
- }
- local.sun_family=AF_UNIX;
- strcpy(local.sun_path, "rmsock");
- unlink(local.sun_path);
- len = strlen(local.sun_path) + sizeof(local.sun_family);
- if(bind(s, (struct sockaddr*)&local, len) == -1) {
- perror("bind");
- exit(1);
- }
- if(listen(s,100) == -1) {
- perror("listen");
- exit(1);
- }
- for(;;) {
- int done, n;
- printf("Waiting for a connection...\n");
- t=sizeof(remote);
- if((s2=accept(s, (struct sockaddr *)&remote, &t)) == -1) {
- perror("accept");
- exit(1);
- }
- printf("Connected.\n");
- done=0;
- do {
- n=recv(s2, str, 1024, 0);
- if(n<=0) {
- if(n<0) perror("recv");
- done=1;
- }
- if(!done) {
- if(!strcmp(str,"hello\n")) {
- send(s2, "Auth required...\n", 17, 0);
- } else
- if(send(s2, "Unknown command\n", 17, 0) < 0) {
- perror("send");
- done=1;
- }
- }
- } while(!done);
- close(s2);
- }
- }
- else
- {
- for(;;) {
- stat("rm",&buf);
- if(buf.st_mtim.tv_sec!=last_mod) {
- kill(getpid(),SIGUSR1);
- }
- sleep(1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment