Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么我的分叉程序在每次分叉后都会加倍?_C_Unix_Fork - Fatal编程技术网

C 为什么我的分叉程序在每次分叉后都会加倍?

C 为什么我的分叉程序在每次分叉后都会加倍?,c,unix,fork,C,Unix,Fork,所以我只想创建一个简单的分叉程序,以每半秒1个的速度分叉5个孩子,然后显示每个分叉完成的日期和时间。。这就是代码的jist int count = 1; while(count <= 5){ int kid = fork(); if(kid == -1){ perror("error in fork"); exit(0); } else if(!kid){ numbytes = read(sockfd, buf, s

所以我只想创建一个简单的分叉程序,以每半秒1个的速度分叉5个孩子,然后显示每个分叉完成的日期和时间。。这就是代码的jist

int count = 1;
while(count <= 5){
    int kid = fork();

    if(kid == -1){
        perror("error in fork");
        exit(0);
    } else if(!kid){
        numbytes = read(sockfd, buf, sizeof(buf)-1);
        buf[numbytes] = '\0';
        printf("%s\n",buf);
    }
    count++;
    usleep(500000); //create per every half second, 500000 = 0.5sec
    close(sockfd);

}


return 0;
int count=1;

而(countA
fork
通常是这种形式

    int pid = fork();

    if( pid == -1 ) { /* error */
        fprintf(stderr, "Error forking: %s", strerror(errno));
        exit(1);
    }
    else if( pid == 0 ) { /* child */
        puts("Child");
        exit(0);
    }

    /* Parent */
    printf("Forked %d\n", pid);
请注意,子进程必须退出,否则它将继续执行程序的其余部分

另一部分是主程序,直到所有子进程都完成为止,否则您将得到。通常是一个循环调用
wait()
,直到不再有子进程为止

int wpid;
int wstatus;
while( (wpid = wait(&wstatus)) != -1 ) {
    printf("Child %d exited with status %d\n", wpid, wstatus);
}
把它们放在一起,下面是如何分叉并等待5个子进程

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

int main() {
    int max_children = 5;

    for( int i = 0; i < max_children; i++ ) {
        int pid = fork();

        if( pid == -1 ) { /* error */
            fprintf(stderr, "Error forking: %s", strerror(errno));
        }
        else if( pid == 0 ) { /* child */
            puts("Child");
            exit(0);
        }

        /* Parent */
        printf("Forked %d\n", pid);
    }

    int wpid;
    int wstatus;
    while( (wpid = wait(&wstatus)) != -1 ) {
        printf("Child %d exited with status %d\n", wpid, wstatus);
    }
}
#包括
#包括
#包括
#包括
#包括
int main(){
int max_children=5;
对于(int i=0;i
因为您一直在父进程和子进程中分叉。子进程完成后是否应该退出?子进程也应该退出吗?否则,当父进程退出时,您将拥有孤立的僵尸进程。@Someprogrammerdude感谢您的快速回复,但现在我很难找出是什么原因重新设置等待和退出。抱歉,这对我来说是一个全新的设置。退出()在?@Karthikeyan.R.SApologize@Jeans之后的块末尾,您应该在else if block and
wait
usleep
之前或之后添加
exit