我想用他们的pid和打印一系列进程burst time.为此,我生成pid使用fork()然后pid使用它getpid().但是,由于fork创建了一个与父进程隔离运行的子进程,因此我没有得到预期的行为.程序应该做的是生成给定的进程number_of_process,然后在特定的结构元素内存储pid和随机burst time值.这是我的代码: -
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<signal.h>
struct process{
int pid;
int bt;
};
int main()
{
int no_of_process,i,new_process;
printf("Enter the number of process\n");
scanf("%d",&no_of_process);
struct process p[no_of_process];
for(i=0;i<no_of_process;i++){
new_process=fork();
p[i].pid = getpid();
p[i].bt = rand()%10;
//kill(getpid(),SIGKILL);
}
for(i=0;i<no_of_process;i++){
printf("process %d and bt %d\n",p[i].pid,p[i].bt);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我试图杀死子进程,但这会停止整个程序.进程数的输出= 2
process 6373 and bt 3
process 6373 and bt 6
process 6374 and bt 3
process 6376 and bt 6
process 6373 and bt 3
process 6375 and bt 6
process 6374 and bt 3
process 6374 and bt 6
Run Code Online (Sandbox Code Playgroud)
预计应该只有2个具有pid和bt(突发时间)的进程.
- 如何在存储pid和bt(突发时间)之后杀死子进程或者它无法完成?
你没有fork正确使用.当您调用它时,子进程继续执行与父进程相同的代码,但获取不同的返回值(0)以指示它是子进程.因此,在您的代码中,子进程都会产生自己的子进程.
通常的用法fork是做类似的事情
new_process=fork();
if(new_process==0)
{
// I am the child
}
else if(new_process==-1)
{
// Something bad happened
}
else
{
// I am the parent
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
524 次 |
| 最近记录: |