c - Linux 中的 fork 和 setsid() 的使用

标签 c linux fork

我有一个示例代码,但我不知道如何弄清楚发生了什么。 我只展示相关部分。问题是make_daemon()

根据我对 fork 的理解,从 close(0) 开始的代码是由应该有 pid == 0 的子进程执行的。

当代码命中return -1时会发生什么?代码是返回到父级还是退出?子p进程代码是否执行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;
}

最佳答案

fork可以返回三种类型的返回值:

  • 正数:这只发生在父级中:它是成功创建的子级的 pid。
  • 零:仅在子级中返回,并指示此代码现在在子级中执行。这不是子进程的 pid,请使用 getpid 获取子进程的 pid。
  • 负值(通常为-1)。这也仅在父级中返回,并指示 fork 由于某种原因失败并且没有创建子级。

至于您的代码的作用:是的,只要确实创建了子项,子项将在 close(0); 处继续。

当您的 cild 命中 return -1 时,它将返回到父级中名为 make_daemon 的任何函数,并在此时继续执行。通常 fork 的子进程会做他们应该做的事情,然后调用 exit 以免扰乱父进程正在做的事情。

关于c - Linux 中的 fork 和 setsid() 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23787166/

相关文章:

c++ - 调用 POCO c++ ServerSocket() 时在 Linux 上出现段错误

linux - 什么是最好的邮件列表包? (Linux)

perl - Perl 中的文件系统事件派生子进程

c - 指针指向的 int 的增量值

c - IA32 到 Y86 汇编代码转换

linux - 为本地文件设置到期日期 - Windows/Linux

c - fork() 调用打印次数超出预期

c - 关于客户端/服务器 echo 程序的上一个问题的后续

c - EOF 保证为 -1 吗?

c - 为什么我的 File.dat 不会被读取和运行,我如何将数据分配给结构? - C