C 通过rsh运行守护进程
我想在Unix的远程机器上作为守护进程运行程序。我有rsh连接,我希望程序在断开连接后运行 假设我有两个程序:util.cpp和forker.cpp util.cpp是一些实用程序,为了我们的目的,让它只是无限根 util.cppC 通过rsh运行守护进程,c,unix,fork,daemon,rsh,C,Unix,Fork,Daemon,Rsh,我想在Unix的远程机器上作为守护进程运行程序。我有rsh连接,我希望程序在断开连接后运行 假设我有两个程序:util.cpp和forker.cpp util.cpp是一些实用程序,为了我们的目的,让它只是无限根 util.cpp int main() { while (true) {}; return 0; } #include <stdio.h> #include <errno.h> #include <stdlib.h> #includ
int main() {
while (true) {};
return 0;
}
#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: do nothing.
}
return 0;
}
forker.cpp获取一些程序,并通过fork()和execve()在separe进程中运行它:
forker.cpp
int main() {
while (true) {};
return 0;
}
#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: do nothing.
}
return 0;
}
forker很快就完成了,bash“没有暂停”,util作为守护进程运行
但如果我跑步:
scp forker remote_server://some_path/
scp program remote_server://some_path/
rsh remote_server 'cd /some_path; ./forker program'
然后一切都一样(即,在远程服务器上,forker正在快速完成,util正在运行),但我的bash在本地机器上暂停。
它正在等待util停止(我检查了它。如果util.cpp返回,它就正常了),但我不明白为什么
有两个问题:
1) Why is it paused when I run it through rsh?
我确信我选择了一些愚蠢的方式来运行守护进程。所以
2) How to run some program as daemon in C/C++ in unix-like platforms.
Tnx
1)当我通过rsh运行它时,为什么会暂停?
当您分叉一个进程时,子进程有它自己的父进程文件描述符的副本。每个子级的文件描述符都引用与父级的相应文件描述符相同的打开文件描述。调用
fork()
之后,在调用execve()
之前,您没有关闭子进程中的标准流(stdin
,stdout
,stderr
),因此它们仍然连接到rsh。在这种情况下,只要远程服务器上的任何进程都持有对这些流的引用,rsh就不会返回。您可以尝试在调用execve()
之前使用关闭标准流,或者在执行forker程序时重定向它们(例如,/forker-program>/dev/null-2>/dev/null-Whell,rsh-remote_-host./forker-program>/dev/null-2>/dev/null关于第二个问题,我想你指的是nohup./program,而不是nohup./forker-program。无论如何,nohup在程序运行之前不会返回。这就是我需要forker的原因。如果你把rsh发送到服务器并在那里写“nohup./program”af请注意,如果关闭会话,程序仍在运行。但如果尝试运行“rsh服务器”nohup./program'再次暂停。如果按ctrl-c,程序将停止。无论如何,我对第一个问题感兴趣。好的,尽管获得了aim.rsh服务器,但仍然不太理解。/program 1>pr.out 2>pr.err&'也解决了我的问题,没有forker。对我来说,'/program&'比'nohup./program'然后注销要容易得多。'这是我通常理解的,对你来说没有区别。