c - 在 c 中执行代码之前从 fork() 打印出多个进程 ID

标签 c fork parent-child

对于一项作业,我应该总共创建四个流程,并在每个流程中打印一个字母倍数。我应该调用 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/

相关文章:

c - 在 C 中缓冲的类型化数据

c - 将双关语输入整数并排序

macos - 为什么我不能在不同的 fork 进程中使用 cocoa 框架?

javascript - 如何在react-native中从子组件(带参数)调用父函数?

c - 定义为宏的标准库函数的参数类型错误

c - 如何检查参数是否传递给 C 中的函数?

c - 为什么在打印 "This is the child process!"后执行停止?

c - 这段关于使用 fork() 在 C 中创建进程的代码会发生什么

java - GWT TextBox、DateBox 等不共享相同的基本输入类

Java:当涉及父/子时,如何获取 ArrayList 中的值?