不存在的进程,fork()
问题描述:
如果我运行这个程序,我会有死去的进程吗?我正在尝试创建一个运行5进程并行的主程序,然后不会得到不可用的进程。麻烦主要是要确定这没有发生。我不太确定我是否正确地做到这一点。我听说最好的做法是通过让你的进程“等待()”来处理已经“fork()”的许多子进程,以确保你没有停止进程。不存在的进程,fork()
#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
void forkChildren(int nrofChildren, int *nr_of_children) {
pid_t pid;
int i;
for(i=0; i<5; i++) {
/* fork a child process */
pid = fork();
(*nr_of_children)++;
/* error occurred */
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
exit(-1);
}
/* successful child */
else if (pid == 0) {
int sleeptime=1; //rand()%10;
printf("I am child: %d \nwith parent: %d \nin loop: %d \nand will sleep for: %d sec\n\n", getpid(), getppid(), i, sleeptime);
sleep(sleeptime);
printf("Ending of child: %d \nwith parent :%d in loop: %d\n\n", getpid(), getppid(), i);
}
/* parent process
else {
wait(NULL); Do I need this to make sure I dont get defunct processes???
} */
}
}
int main(int argc, char *argv[]) {
srand((unsigned int)time(NULL));
int nr_of_children=0;
if (argc < 2) {
/* if no argument run 5 childprocesses */
forkChildren(5, &nr_of_children);
} else {
forkChildren(atoi (argv[1]), &nr_of_children);
}
wait(NULL);
printf("End of %d, with %d nr of child-processes\n\n", getpid(), nr_of_children);
return 0;
}
答
看看使用daemon()命令将您的应用放在后台,然后使用pthreads来管理并行性。
NAME 守护 - 在后台运行
概要 的#include
int daemon(int nochdir, int noclose);
功能测试宏要求的glibc(见 feature_test_macros(7)):
daemon(): _BSD_SOURCE || (_XOPEN_SOURCE && _XOPEN_SOURCE < 500)
描述 daemon()函数用于程序希望从控制终端分离自己并在后台运行的系统守护进程 。
If nochdir is zero, daemon() changes the process’s current working directory to the root directory ("/"); otherwise, If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made
这些文件描述符。
*全部*过程在终止后变为无效。如果你“等待”他们,他们会在很短的时间内成为僵尸。如果你离开或从主队返回,他们将在很短的时间内成为僵尸,因为他们将被等待他们的初始化人接受。 – 2013-03-23 13:51:15
为什么不使用返回值来将生成的孩子的数量传递给调用者,而不是使用具有指向结果的愚蠢的'* nr_of_children'指针的void()函数? – wildplasser 2013-03-23 13:54:16
@wildplasser啊哈,这是一个想法,我没有想过,谢谢:-) – patriques 2013-03-23 13:56:38