我最近开始学习如何在 Linux 下用 C 编程,并编写了以下代码来创建一些进程:
void generate()
{
int pid;
for(int i=1;i<=10;i++)
{
pid = fork();
}
if (pid<0)
{
printf("Error Fork");
exit(1);
}
if(pid == 0)
{
printf("Fiu pid: %d --- Parinte pid: %d\n", getpid(), getppid());
//count ++;
}
if(pid > 0 )
{
printf("Parinte pid: %d\n", getpid());
//count++;
wait();
}
}
问题是:我应该如何声明/增加 count 变量以打印函数创建的进程总数?
最佳答案
很简单。 Fork
为每个父节点生成一个子节点。因此答案是 2^10 或 1024。
在 fork
之后放置一个 printf
并注释掉其他无关的输出。运行方式
./a.out | sort | uniq | wc
输出是 1024。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
void generate()
{
int pid;
for(int i=1;i<=10;i++)
{
pid = fork();
printf("%d\n", getpid());
}
if (pid<0)
{
//printf("Error Fork");
exit(1);
}
if(pid == 0)
{
//printf("Fiu pid: %d --- Parinte pid: %d\n", getpid(), getppid());
//count ++;
}
if(pid > 0 )
{
//printf("Parinte pid: %d\n", getpid());
//count++;
wait(NULL);
}
}
int main(int argc, char *argv[])
{
generate();
return(0);
}
关于c++ - C/C++多进程访问同一个变量的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22770097/