对于一项作业,我应该总共创建四个流程,并在每个流程中打印一个字母倍数。我应该调用 fork()
两次来完成此操作。
我已经能够为每个过程多次打印字母。问题出现在分配细节的第二部分。我应该在打印出字母之前打印出每个正在运行的进程的进程 ID。输出应如下所示:
Process ID: 123
Process ID: 124
Process ID: 125
Process ID: 126
AAAAABBBBBCCCCCDDDDD
我认为这可以通过使用以下代码来完成:
pid_t child1, child2;
child1 = fork();
child2 = fork();
printf("Process created. ID: %d\n", getpid());
if(child1 == 0) { // print letters }
else if(child2 == 0) { //print letters }
else { // call waitpid and print more letters }
我想因为 fork()
在 child1 = fork()
行拆分,然后在 child2 = fork()
再次拆分,然后转到下一行,它会打印出所有内容,然后点击 if-else
语句。但是,这是我的输出:
Process created. ID: 20105
Process created. ID: 20107
AAProcess created. ID: 20106
AAABBBProcess created. ID: 20108
BBCCCCCDDDDD
如何确保我的 Process Created 打印语句首先执行?
最佳答案
child1 = fork(); // Fork 1 here
child2 = fork(); // Fork 2 here after first fork .!!
上面的 fork 将创建四个进程。但是您正在与原始 parent 以及您的第一个 child 一起做第二个 fork()
。我想这不是你真正需要做的。您只需要从原始父进程开始三个进程。
看给定的例子:这里我创建了 2 个子进程,所有进程数都是 3 [With main]。在这里,我尝试提供具有所需输出的引用解决方案。
#include <unistd.h> /* Symbolic Constants */
#include <sys/types.h> /* Primitive System Data Types */
#include <stdio.h> /* Input/Output */
#include <sys/wait.h> /* Wait for Process Termination */
#include <stdlib.h> /* General Utilities */
int main()
{
pid_t childpid1,childpid2; /* variable to store the child's pid */
/* now create new process */
childpid1 = fork();
if (childpid1 >= 0) /* fork succeeded */
{
if (childpid1 == 0) /* fork() returns 0 to the child process */
{
printf("1 : %d \n",getpid());
printf("AA");
}
else /* fork() returns new pid to the parent process */
{
childpid2 = fork();
if (childpid2 >= 0) /* fork succeeded */
{
if (childpid2 == 0) /* fork() returns 0 to the child process */
{
printf("2 :%d \n",getpid());
int stat;
waitpid(childpid1, &stat, 0);
printf("BB");
}
else /* fork() returns new pid to the parent process */
{
printf("3 : %d \n",getpid()); // This is the Original parent of ALL
int stat2;
waitpid(childpid2, &stat2, 0);
printf("CC");
}
}
}
}
return 0;
}
关于c - 在 c 中执行代码之前从 fork() 打印出多个进程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28339283/