为什么这里的孩子处理不打印任何东西?

时间:2009-02-28 01:29:58

标签: c++ fork parent-child

假设之前已经声明了所有变量......因为它们已经被声明了。子进程不打印任何让我觉得它没有被执行的东西。父进程运行正常,尽管它没有获得共享内存。 我为这段代码的长度道歉...

// create 5 child process
for(int k=0;k<5;k++){

    // fork a child process
    pid = fork();

    // error occured on fork
    if (pid < 0) {
        fprintf(stderr, "Fork Failed");
        return 1;
    }
    // this is what the child process will run
    else if (pid == 0) {
        //create a shared mem segment
        segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR);

        //attach the shared memory segment
        shared_memory = (char *) shmat(segment_id, NULL, 0);

        printf("this is child");

        double x = 0;
        double sum = 0;

        // Run process that sums the function
        for(int i=0; i<n; i++){
            // get random number in range of x1-x2
            x = rand()%(x2 - x1 + 1) + x1;
            sum = sum + f(x);
        }

        //write output to the shared memory segment
        sprintf(shared_memory, "%f", sum);
        execlp("/bin/ls", "ls", NULL);

     }

    // this is what the parent process will run
    else {

       //print output from shared memory
        printf("\n*%s", shared_memory);

        //detach shared memory
        shmdt(shared_memory);

        //Here we add the shared memory to the array
        // To add together at the end
        // but since I cant get the memory to share
        // the array can't be implemented

        //remove the shared memory segment
        shmctl(segment_id, IPC_RMID, NULL);

        wait(NULL);
    }
} // End of for statement

3 个答案:

答案 0 :(得分:10)

C stdout流在内部缓冲数据。可能是你的“这是孩子”的消息被缓冲了,缓冲区没有被execlp刷新,所以它就消失了。在printf之后尝试fflush(stdout);。顺便说一下,你也应该在fork()之前执行此操作,这样孩子和父母都不会尝试在fork之前编写缓冲输出。

答案 1 :(得分:3)

打印到stderr它没有缓冲。

fprintf(stderr,"Plop\n");

此外,共享内存中的东西(segment_id,shared_memory)未在父级中初始化(或者如果它与子级不同)。

此外,当孩子仍在处理时,父母可能会破坏共享内存。父母应该先等待然后处理孩子产生的数据。

答案 2 :(得分:-1)

首先删除所有共享内存,然后查看子进程是否可以成功printf。

通过该代码段的外观,您正在初始化子进程中的shared_memory,但不在父进程中。