c - Running daemon through rsh -
i want run program daemon in remote machine in unix. have rsh connection , want program running after disconnection.
suppose have 2 programs: util.cpp , forker.cpp.
util.cpp utility, our purpose let infinite root.
util.cpp
int main() { while (true) {}; return 0; }
forker.cpp takes program , run in separe process through fork() , execve():
forker.cpp
#include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char** argv) { if (argc != 2) { printf("./a.out <program_to_fork>\n"); exit(1); } pid_t pid; if ((pid = fork()) < 0) { perror("fork error."); exit(1); } else if (!pid) { // child. if (execve(argv[1], &(argv[1]), null) == -1) { perror("execve error."); exit(1); } } else { // parent: nothing. } return 0; }
if run:
./forker util
forker finished quickly, , bash 'is not paused', , util running daemon.
but if run:
scp forker remote_server://some_path/ scp program remote_server://some_path/ rsh remote_server 'cd /some_path; ./forker program'
then same (i.e. @ remote_sever forker finishing quickly, util running) bash in local machine paused. waiting util stopping (i checked it. if util.cpp returning ok.), don't understand why?!
there 2 questions:
1) why paused when run through rsh?
i sure chose stupid way run daemon. so
2) how run program daemon in c/c++ in unix-like platforms.
tnx!
1) why paused when run through rsh?
when fork process, child process has own copy of parent's file descriptors. each of child's file descriptors refers same open file description corresponding file descriptor of parent. after call fork()
not closing standard streams (stdin
, stdout
, stderr
) in child process before call execve()
still connected rsh. may case rsh not return long process on remote server holding reference these streams. try closing standard streams using fclose()
before call execve()
or redirect them when execute forker program (i.e. ./forker program >/dev/null 2>/dev/null </dev/null
).
2) how run program daemon in c/c++ in unix-like platforms.
according wikipedia, nohup
used run commands in background daemons. there several daemon related questions on site can refer information.
from wikipedia:
nohup posix command ignore hup (hangup) signal, enabling command keep running after user issues command has logged out. hup (hangup) signal convention way terminal warns depending processes of logout.
if program run daemon, can possibility of calling daemon()
within program. daemon()
convenience function exists in unix systems.
from daemon(3) man page:
the daemon() function programs wishing detach controlling terminal , run in background system daemons.
should function not exist or should there instances program not run daemon, forker program can modified 'daemonize' other program.
without making changes code, try following:
rsh remote_server 'cd /some_path; nohup ./forker program >program.out 2>program.err </dev/null &'
Comments
Post a Comment