c - 如何从 C 中的父进程分离 fork 进程

标签 c shell unix exec fork

所以我正在用 C 设计一个基本的 UNIX shell。

    signal(SIGCHLD, handler);
        pid = fork();
        switch (pid) {
        case -1: printf("Fork failed; cpid == -1\n");
        break;

        case 0: child_pid = getpid();
                argv[0] = prog;
        argv[1] =NULL;
        //exit(0);
        sid = setsid();
        execv(absPath,argv);        
        //printf("%d: this is the child, pid = %d\n", i, child_pid);
        //sleep(1);
        //exit(0);
        break;

        default: printf("This is the parent: waiting for %d to finish\n", pid);
        waitpid(pid, NULL, WNOHANG);
        printf("Ttttthat's all, folks\n");
        //break;
        }
        //execv(absPath,argv);
        //printf("CHILD PROCESS");
    }

}
void handler(int sig)
{
  pid_t pid;

  pid = wait(NULL);

  printf("Pid %d exit.\n", pid);
  exit(0);
}

但它仍然在同一个 shell 中执行 fork 进程,尽管在“default”子句之后。

你能帮我让它作为后台进程运行吗?谢谢!

P.S:这只是一个片段。

最佳答案

评论一些明显的错误:

  • 在子进程中执行 exit(0);从而立即退出子进程。删除此行。
  • 我认为为了清楚起见,您应该调用 execv()像这样execv(argv[0], argv);

  • 编辑:
    Read the following解决从子进程 fork 的问题。

    关于c - 如何从 C 中的父进程分离 fork 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10311879/

    相关文章:

    c++ - 找不到 boost 库

    linux - 排序命令不适用于大文件

    C内存分配问题

    regex - 如何编写这个 grep 正则表达式

    python - 从 shell 和 python 中的行中删除字符串

    unix - 如何在 Unix Shell 脚本中进行并行处理?

    c++ - 如何开始使用多线程编程?

    C宏连接

    填充数组时崩溃

    C _Generic 默认返回参数