gpt4 book ai didi

c - 为什么 getppid 和 getpid 返回相同的值

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:04 24 4
gpt4 key购买 nike

/*  In alarm.c, the first function, ding, simulates an alarm clock.  */

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

static int alarm_fired = 0;

void ding(int sig)
{
alarm_fired = 1;
}

/* In main, we tell the child process to wait for five seconds
before sending a SIGALRM signal to its parent. */

int main()
{
pid_t pid;

printf("alarm application starting\n");

pid = fork();
switch(pid) {
case -1:
/* Failure */
perror("fork failed");
exit(1);
case 0:
/* child */
sleep(5);
printf("getppid: %d\n", getppid()); // Question: why this line produces the same value as getpid?
kill(getppid(), SIGALRM);
exit(0);
}

/* The parent process arranges to catch SIGALRM with a call to signal
and then waits for the inevitable. */

printf("waiting for alarm to go off\n");
(void) signal(SIGALRM, ding);

printf("pid: %d\n", getpid()); // Question: why this line produces the same value as getppid?
pause();
if (alarm_fired)
printf("Ding!\n");

printf("done\n");
exit(0);
}

我已经在 Ubuntu 10.04 LTS 下运行了上面的代码

> user@ubuntu:~/Documents/./alarm
> alarm application starting
> waiting for alarm to go off
> pid: 3055
> getppid: 3055
> Ding!
> done

最佳答案

嗯,因为在 child 中您调用 getppid 返回 child 的 parent-pid。在 parent 中调用 getpid 返回parent's (own) pid

从子级调用getppid(获取父级 pid)与从父级调用 getpid 是一样的。

所以值是一样的。这不是直截了当和意料之中的吗?

关于c - 为什么 getppid 和 getpid 返回相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6577529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com