c - Fork() 子链

标签 c fork wait

我有以下代码,它使用 fork() 创建定义数量的子线程:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

#define NUM_THREADS     4

int main()
{
        int i;
        pid_t pid;
        for(i = 0; i < NUM_THREADS; i++){ //Do this equal to the number of threads
            pid = fork();//Use this to avoid multiple forking

            if(pid == 0){ //If it's a child process
                    printf("Hello World! Greetings from PID: %ld! :D\n", (long)getpid()); //getpid returns the pid of the process
                    exit(0); //Exit the process
            }else if(pid == -1){
                    printf("Oh no! Could not fork! :( Exiting!\n");
                    return 0;
            }
    }
    int status;
    for(i = 0; i < NUM_THREADS; i++){
            wait(&status);//wait until all the children processes have finished.
    }
    printf("All done! I am the parent process! My PID is: %ld if you were curious! \n", (long)getpid());

    return 0;

这是作为示例提供给我们的。 它的输出是这样的:

Hello World! Greetings from PID: 118358! :D
Hello World! Greetings from PID: 118359! :D
Hello World! Greetings from PID: 118360! :D
Hello World! Greetings from PID: 118362! :D

我想做的是让父进程创建一个子进程,而不是让 1 个父进程有多个子进程,子进程创建一个子进程,依此类推定义的线程数。我该怎么做?

最佳答案

您的示例代码使用 fork() 的返回值来区分父子。它继续在父级中迭代(假设 fork() 没有报告错误),并且它在 exit() 中没有迭代(在发出一些输出之后) child 。这完全是例行公事。

您打算做的事情并没有太大的不同;你描述的主要只是交换 parent 和 child 的角色。事实上,您的工作更简单,因为每个 parent 只需要为一个 child wait()。它可以在循环内或循环外执行此操作,前提是如果最后一个子 wait() s 那么它应该期望调用指示错误,因为该子没有自己的任何子.但是,如果父级没有从循环内部exit()return,那么它确实需要跳出而不是进一步迭代。

关于c - Fork() 子链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40136119/

相关文章:

c - Sphinx - 单词边界

c - Pop() 方法总是给出堆栈中的第一个元素而不删除它

c - C语言中如何在一定时间限制后准确杀死子进程?

c - 写时复制如何在 fork-exec 中工作?

子进程没有终止

C#:等到进度条完成绘制

bash:在继续之前等待特定的命令输出

c - 提高我实现计数排序的时间复杂度(C)

c - 关于循环缓冲区C实现的问题

c - 如何编写并行下载的代码?