1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
|
int main(void)
{
/* Our process ID and Session ID */
pid_t pid, sid;
/* Fork off the parent process */
pid = fork();
if (pid < 0)
{
exit(EXIT_FAILURE);
}
/* If we got a good PID, then
we can exit the parent process. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* Change the file mode mask */
umask(0);
/* Open any logs here */
ofstream outfile("/root/log.txt");
/* Create a new SID for the child process */
sid = setsid();
if (sid < 0)
{
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Change the current working directory */
if ((chdir("/")) < 0)
{
/* Log the failure */
exit(EXIT_FAILURE);
}
/* Close out the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* Daemon-specific initialization goes here */
int s, s2, len;
socklen_t t;
struct sockaddr_un local, remote;
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
local.sun_family = AF_UNIX;
strcpy(local.sun_path, SOCK_PATH);
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, 5) == -1)
{
perror("listen");
exit(1);
}
pid_t pidf,pidc;
int stat=0;
int execReturn =0;
int n;
char str[100];
vector<int> pidV;
while (1)
{
stat =0;
execReturn=0;
s2 = accept(s, (struct sockaddr *)&remote, &t);
if(s2== -1)
{
perror("accept");
outfile<<strerror(errno)<<endl;
exit(1);
}
pidc = fork();
if(pidc!=0)
pidV.push_back(pidc);
if(pidc == 0)
{
close(s);
n = recv(s2, str, 100, 0);
str[n]='\0';
outfile<<"Message is "<<str;
pidf = fork();
if (pidf == 0)
{
close(s2);
execReturn =execl("/root/haresh/cpp/test.sh","test.sh",NULL);
outfile<<"Errror"<<endl;
_exit(-1);
}
else if (pidf > 0)
{
int id = waitpid(pidf,&stat,0);
int sat = WEXITSTATUS(stat);
outfile<<"status is "<<sat<<"pid is "<<pidf<<endl;
char stg[32];
sprintf(stg,"%d",sat);
send(s2,stg,strlen(stg), 0);
close(s2);
_exit(0);
}
}
else if(pidc > 0)
{
close(s2);
//REAP ALL CHILDREN
/*
vector<int>::iterator beg = pidV.begin();
while(beg!=pidV.end())
{
int id = waitpid(*beg,&stat,WNOHANG);
if(id!=0)
{
beg = pidV.erase(beg);
}
else
{
++beg;
}
}
*/
sleep(5); /* wait 30 seconds */
}
exit(EXIT_SUCCESS);
}
|