Home > database >  Forking in a loop and printing the correct process number
Forking in a loop and printing the correct process number

Time:11-08

The C script is supposed to take x amount of CPU bound forks and x amount of IO bound forks, so then lets say 10 total processes if you there's 5 of each. If I fork 10 times, then 5 of those should go to working on the CPU bound "fake work" and 5 of those should go to the IO bound "fake work". Waitstats is a custom function that serves the purpose of wait while also displaying rtime and wtime.

My problem is that I've tried multiple configurations and I'm not sure how to get the Process Number printf to correctly print, only 10 times, if there's only 10 forks? I also feel as if I'm not doing my fake work correctly for the CPU/IO bound work.

Any help here would be appreciated!

`

int main(int argc, char* argv[])
{

    int cpuNum = atoi(argv[2]);
    int ioNum = atoi(argv[4]);

    int const MAX_PROC = cpuNum   ioNum;
    printf("\nMax Proc %d", MAX_PROC);


    int totRunTime = 0;
    int totWaitTime = 0;

    uint rTime = 0;
    uint wTime = 0;

    int pid = 0;
    //Create Max_Proc Forks
    for(int n=0; n < MAX_PROC; n  ) 
    {
        pid = fork();
        //If Child, Exceute Command
        if(pid == 0)
        {
            break;
        }

    }

    if (cpuNum > 0) {
        //CPU Busy Work
        for (volatile int i = 0; i < 1000000000; i  ){}
        cpuNum--;
    }
    else if (ioNum > 0) {
        //IO Busy Work
        sleep(200);
        ioNum--;
        
    }
    

    for(int p=0; p < MAX_PROC; p  ) 
    {
        printf("\n Process %d finished", p);
        if(waitStats(0, &rTime, &wTime) >= 0) 
        {
            totRunTime  = rTime;
            totWaitTime  = wTime;
        }

    }

    printf("\nAverage rtime %d, wtime %d", rTime, wTime);


    exit(0);

}

`

I've tried multiple configurations, but can't seem to get the printf to print the correct process/fork number. For instance forking 10 times would mean I would need to printf every time one of those forks finished their task (10 total times).

CodePudding user response:

The code shown doesn't print pids, so I'm assuming you mean "process number" as in 1st child, 2nd child etc.

Every one of your processes is running this:

for(int p=0; p < MAX_PROC; p  ) 
{
    printf("\n Process %d finished", p);
    ...

So it looks like each process will print the numbers 0 .. MAX_PROC-1 (with no indication of which pid is printing)

CodePudding user response:

Have you tried putting the waitStats for loop inside of your "Create Max_Proc Forks" for loop? So then basically everything should be inside of the first loop, probably giving you a good way to keep track of the process number?

  • Related