c - fork 和pid

标签 c linux fork

代码:

int main(void) 
{
    printf("pid: %d\n", getpid());
    pid = fork();


    if (pid < 0) {
        fprintf(stderr, "Fork Failed!");
        exit(-1);
    } else if (pid == 0) {
        execv("sum", argv);
    } else {
        printf("  pid: %d\n", pid);
        wait(NULL);
    }
}

输出:

pid: 280
   pid: 281

问题:

为什么两个pid不同。我认为它们应该相同,因为父级是在 else block 中执行的,而父级是在 fork 之前执行的,所以它们应该相同,不是吗?

最佳答案

RETURN VALUE
       On success, the PID of the child process is returned in the parent, 
       and 0 is returned in the child.  On failure, -1 is returned in the parent,
       no child process  is  created,  and  errno  is  set appropriately.

因此,在父进程中,fork() 返回创建的子进程的 pid。

关于c - fork 和pid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6233707/

相关文章:

c++ - 为什么在 Windows 中编译的库在 Linux 操作系统中不起作用?

linux - JAVA_HOME 设置不正确。如何重置?

c - c 中 fork() 的输出

c++ - Boost.Log 和创建守护进程; `fork` 不允许?

c - 尝试测试 fgets() 时出现段错误

c - 使用原型(prototype)+定义而不是仅仅使用定义可以加快程序速度吗?

c - 词法分析器输出问题

c - 打印文本而不是 C 枚举中的值

linux - 如何对收到的邮件执行 PHP 脚本?

进程 fork 时的 Java 文件管理