Hi everyone , i have this code and i know that the problem is in the While loop but i cant clearly identify the problem , i know its about the child processes . but i need more clarity why the loop is making problems.
please help thanks allot.

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

#define MAXCOUNT 100000000
#define NUM_CHILDREN 4
#define SHMSEGSIZE sizeof(int)

int main() {
    int i, shmID, *shared_mem, count = 0;
    int pid[NUM_CHILDREN];
    shmID  = shmget(IPC_PRIVATE, SHMSEGSIZE, IPC_CREAT | 0644);
    shared_mem  = (int *)shmat(shmID, 0, 0);
    *shared_mem = 0;

    for (i=0; i < NUM_CHILDREN; i++) {
        pid[i] = fork();

        if (pid[i] == -1) { return EXIT_FAILURE; }
        if (pid[i] == 0) {
            while (*shared_mem < MAXCOUNT) {
                *shared_mem += 1;
            printf("%ites inc value with %i!\n", i, count);
            return EXIT_SUCCESS;
    for (i=0; i < NUM_CHILDREN; i++) {
        waitpid(pid[i], NULL, 0);
    printf("Shared Memory = %i - MAXCOUNT = %i\n", *shared_mem, MAXCOUNT);
    shmctl(shmID, IPC_RMID, 0);
    return EXIT_SUCCESS;

Recommended Answers

All 3 Replies

And what problems, specifically are you having? From the title of this post, you seem to think that shared memory is a problem? Why do you think that? Please be more clear about your issues. I see your code - you create a shared memory segment, fork, but you don't do anything with it.

i want to manage how the child proceses work inside the while loop

If fork() returns 0, then the process that got that is the child, otherwise the forking process will get the child's pid, and it is the one that wants to know when the child terminates so you don't end up with a zombie process (the dead child). That's what the waitpid() process does. There are some subtleties related to that which you will want to research in any case. RTFM - read that fine man page! :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.