Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

c - 每n秒更改一次PID的程序(Program that changes PID every n seconds)

I'm new to system programming in C.

(我是C语言系统编程的新手。)

Here I'm trying to write a program that changes its PID every (n=2) seconds.

(在这里,我正在尝试编写一个程序,该程序每(n = 2)秒更改其PID。)

But while compiling, I get every time, the same PID.

(但是在编译时,我每次都会得到相同的PID。)

The PID never changes.

(PID永不更改。)

Does anyone have an idea please ?

(请问有人有主意吗?)

Here is my code:

(这是我的代码:)

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

int main(){

printf("Programme qui change de PID toutes les deux secondes 
");
pid_t fils;

while(1){
    printf("I'm %d
",(int)getpid());
    sleep(5);
    fils = fork();
    if(fils < 0){
        perror("Fork child 
");
        exit(1);
    }
    else if (fils ==0 )
        exit(0); 

}
return 0;
}
  ask by Hajar ELKOUMIKHI translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

the reason the PID is not changing is because a process pid never changes.

(PID不变的原因是进程pid永远不变。)

and the code is always in the parent process when checking the value of the PID.

(并且在检查PID值时,代码始终在父进程中。)

Now, each child process will receive its' own PID.

(现在,每个子进程将收到其自己的PID。)

You could be having the child get/display its' PID before exiting.

(您可能让孩子在退出前获取/显示其PID。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...