我有一个示例代码,我不知道如何弄清楚发生了什么。我只展示相关的部分。问题出在make_daemon()上。
根据我对forking的理解,从close(0)开始的代码是由应该具有pid == 0的子代执行的。
当代码命中return -1时会发生什么?代码是返回到父级还是退出?子进程代码是否在Monitor()中执行if(share)?
这段代码摘自mdadm中的Monitor.c。
提前感谢您的帮助。
int Monitor( struct mddev_dev *devlist,
char *mailaddr, char *alert_cmd,
struct context *c,
int daemonise, int oneshot,
int dosyslog, char *pidfile, int increments,
int share )
{
if (daemonise) {
int rv = make_daemon(pidfile);
if (rv >= 0)
return rv;
}
if (share)
if (check_one_sharer(c->scan))
return 1;
/* etc .... */
}
static int make_daemon(char *pidfile)
{
int pid = fork();
if (pid > 0) {
if (!pidfile)
printf("%d\n", pid);
else {
FILE *pid_file;
pid_file=fopen(pidfile, "w");
if (!pid_file)
perror("cannot create pid file");
else {
fprintf(pid_file,"%d\n", pid);
fclose(pid_file);
}
}
return 0;
}
if (pid < 0) {
perror("daemonise");
return 1;
}
close(0);
open("/dev/null", O_RDWR);
dup2(0,1);
dup2(0,2);
setsid();
return -1;
}发布于 2014-05-21 23:20:29
fork可以返回三种类型的返回值:
getpid获取该子对象的pid。-1)。这也是仅在父级中返回的,表示无论出于何种原因,fork都失败了,并且没有创建子进程。至于你的代码做了什么:是的,如果确实创建了一个孩子,那么这个孩子将继续留在close(0);。
当您的cild命中return -1时,它将返回到父函数中调用make_daemon的任何函数,并将在该点继续执行。通常情况下,派生的子代会做他们应该做的任何事情,然后调用exit,这样就不会搞砸父代正在做的事情。
https://stackoverflow.com/questions/23787166
复制相似问题