我正在读一本关于操作系统的书,并且对 C 编程也相当陌生(往往会使事情变得复杂),但我很好奇为什么当每个子项都是通过 fork() 创建时我无法打印递增的 i 值。它与子进程有关还是其他原因?提前致谢。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main ()
{
pid_t pid;
int i = 1;
pid = fork();
pid = fork();
pid = fork();
pid = fork();
if (pid == 0) {
printf("got child %d\n", i);
i++;
}
}
最佳答案
使用 getpid()
和 getppid()
获取父进程和子进程 ID。
示例为here
int main()
{
int i;
printf("hello before fork \n");
printf("i : %d\n",i);
i=fork();
printf("\n");
if(i==0)
{
printf("Child has started\n\n");
printf("child printing first time \n");
printf("getpid : %d getppid : %d \n",getpid(),getppid());
sleep(5);
printf("\nchild printing second time \n");
printf("getpid : %d getppid : %d \n",getpid(),getppid());
}
else
{
printf("parent has started\n");
printf("getpid : %d getppid : %d \n",getpid(),getppid());
printf("\n");
}
printf("Hi after fork i : %d\n",i);
return 0;
}
Output:
[04mca8@LINTEL pp]$ ./a.out hello before fork i : 134514088
Child has started
child printing first time getpid : 8354 getppid : 8353
parent has started getpid : 8353 getppid : 5656
Hi after fork i : 8354 [04mca8@LINTEL pp]$ child printing second time getpid : 8354 getppid : 1 Hi after fork i : 0
关于c - 在 fork() 之后打印子编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12461808/