c - 我们如何使用 fork 创建 3 个父级和不同的子级

标签 c

我们如何使用 fork() 创建多个父级,对于每个父级,我们为子级调用 fork() 我们如何管理子级,如何管理他们的地址

For parent proceess i make this function

printf("\n Enter no of Parent processes:");
    scanf("%d",&p);
          for(i=0;i<p;i++)
        { 
           pid=fork();
if(pid==0)
    {
    exit(0);        
        }
else
        {
//parent process is %d",getpid())
        }
}

创建不同父级的多个子级如何管理

最佳答案

以下建议代码:

  1. 干净地编译
  2. 记录了包含每个头文件的原因
  3. 执行所需的功能
  4. 在所有子进程退出之前不会退出
  5. 正确检查错误

现在是建议的代码。

#include <stdio.h>      // scanf(), printf(), perror()
#include <stdlib.h>     // exit(), EXIT_FAILURE, EXIT_SUCCESS
#include <unistd.h>     // fork(), pid_t
#include <sys/types.h>
#include <sys/wait.h>   // waitpid()
#include <string.h>     // memset()


int main( void )
{
    unsigned int numProcesses;

    printf("\n Enter no of Parent processes:");
    if( 1 != scanf("%u",&numProcesses) )
    {
        perror( "scanf for number of processess failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    pid_t childPid[ numProcesses ];
    memset( childPid, '\0', numProcesses*sizeof(pid_t) );

    unsigned i;
    for( i=0; i< numProcesses; i++ )
    {
        childPid[i] = fork();
        switch( childPid[i] )
        {
            case 0:  // child
                {
                    pid_t childchildPid = fork();
                    switch ( childchildPid )
                    {
                        case 0: // child child
                            exit( EXIT_SUCCESS );
                            break;

                        case -1: // fork error
                            perror( "fork by child failed" );
                            exit( EXIT_FAILURE );
                            break;

                        default:  // parent of child child
                            {
                                int status;
                                waitpid( childchildPid, &status, 0 );
                                exit( EXIT_SUCCESS );
                            }
                            break;
                    }
                }
                break;

            case -1: // fork error
                perror( "fork by parent failed" );
                break;

            default:

                break;
        } // end parent switch
    } // end while loop

    int status;

    for( unsigned j = 0; j < i; j++ )
    {
        if( childPid[j] )
        {
            waitpid( childPid[j], &status, 0 );
        }
    }

    return 0;
} // end function: main

关于c - 我们如何使用 fork 创建 3 个父级和不同的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45925139/

相关文章:

C 程序 - 链表问题

c - 如何分配1位值?

c - 在没有 MAX_ELEMENTS 的情况下初始化数组是否更好?

凯撒哈佛CS50X

c - 链表故障列表未链接到头指针

c - scanf 终止程序

c - 如何将字符串分成唯一字符/字符串的数组

c - 信号处理C语言编程

c++ - 将 GCC IR 转换为 LLVM IR

c - 使用 c 在文本文件中切换项目