【发布时间】:2017-09-06 14:09:06
【问题描述】:
我想用pid 和burst time 打印一系列进程。为此,我使用fork() 生成pid,然后使用getpid() 得到它pid。但是,由于 fork 创建了一个与父进程隔离运行的子进程,因此我没有得到预期的行为。程序应该做的是为给定的number_of_process 生成进程,然后将pid 和randomburst 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;
}
我试图杀死子进程,但这会停止整个程序。 进程数的输出 = 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
预计应该只有 2 个具有 pid 和 bt(突发时间)的进程。
- 如何在存储 pid 和 bt(burst time) 后立即杀死子进程,否则无法完成?
【问题讨论】:
-
你的子进程和父进程做同样的事情,所以你会得到你不想要的行为。测试
new_process中的值,如果它为零(子)或不为零(父),则执行不同的操作。注意getpid()返回当前进程的PID。 -
是的,我也想过同样的事情。由于内存是共享的,这就是为什么该结构为每个进程存储 5 个元素,然后每个进程运行循环 5 次。但是我怎样才能得到这样的PID而不面临这个问题并且仍然只有给定的号码。进程,这样一旦创建了进程并且我得到了它的 pid,我就可以完成它的执行。有没有办法做到这一点?但是,在这种情况下,我必须弄清楚如何存储 pid,因为子进程和父进程都使用不同的结构。这可能吗?
-
@ZameerHaque 内存不在进程之间共享——它们是完全独立的。
-
@ChrisTurner 谢谢。这就是我真正想说的。那么我如何让两个进程共享相同的结构,以便只创建 2 个进程并将其存储在 no_of_process = 2 的结构中。
-
@ZameerHaque 您根据下面的许多答案检查
fork的返回值,并在父进程中将 PID 存储在结构中。