trouble with loop counting


 
Thread Tools Search this Thread
Top Forums Programming trouble with loop counting
# 1  
Old 11-06-2011
trouble with loop counting

HI there,

I am trying to count manually what this code does but I am stuck and I don't learly see the result. The code works and it compiles and runs but I just don't follow the value of var.

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

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

    int var = 0;
    pid_t p;
    
    while(++var <5){/*as long as it is less than this it will do fork*/
        if((p=fork()) < 0){
        perror("fork error");
        exit(1);
        }else if(p ==0){ /*if it is the child*/
            var--; /*count down*/
        }
        else{
            if(waitpid(p,NULL,0) != p){/*if waipid is not equal p*/
                perror("waitpid error");
                exit(1);/*exit with status signal1*/
            }/*end if*/
        var++;
        } /*end if/else*/
        var++;
    }/*end while*/
    printf("pid=%d, ppid=%d var=%d, p=%d\n", getpid(), getppid(), var, p);
    exit(0);
}/*end main*/

I understand that in the while condition it says that it should not do something more than 4 times in this case it will fork 4 times. Then in the second if statement it says that if p is the child then we count down (var--) but and yet again at right before closing the while statement we use the counter (var++) again does this mean that whatever was added in the beginning to (++var) at the beginning of the loop then gets subtracted (--var) in the if statement and then added again (var++) just before while?. I cannot follow, can someone give me some insight into how counting the loop and what the code does?

BR,
Bluetxxth

Last edited by bluetxxth; 11-06-2011 at 04:34 PM.. Reason: title
# 2  
Old 11-06-2011
This code is intentionally obtuse. They modify the same counting variable many times per loop. They allow the child to continue looping after fork() -- meaning, the child itself will call fork() on the next loop! And the child will have its own, independent value of var!

The most effective way I see to tackle this program is brute force. Make a big chart of what changes when. Mentally work your way through the program and fill it out.

Their random indenting makes it impossible to see where anything begins or ends, too; tis should help.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<wait.h>

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

    int var = 0;
    pid_t p;
    
    while(++var <5)
    {/*as long as it is less than this it will do fork*/
        if((p=fork()) < 0)
        {
            perror("fork error");
            exit(1);
        }
        else if(p ==0)
        { /*if it is the child*/
            var--; /*count down*/
        }
        else
        {
            if(waitpid(p,NULL,0) != p){/*if waipid is not equal p*/
                perror("waitpid error");
                exit(1);/*exit with status signal1*/
            }/*end if*/

            var++;
        } /*end if/else*/
        var++;
    }/*end while*/

    printf("pid=%d, ppid=%d var=%d, p=%d\n", getpid(), getppid(), var, p);
    exit(0);
}/*end main*/

# 3  
Old 11-06-2011
Hi there,

Thnx for your answer, I kind of imagined that it was going to be complicated... ;-) so I am drawing now..

BR,
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Considerable trouble with for loop in combination with awk

I have the text file where each line has the format: chr10 101418889 101418904 0.816327 Right now the interval between column 2 and 3 is 15. I only want the two consecutive positions starting at position 1, write it to a file, then move up one position write to file etc. So that: ... (1 Reply)
Discussion started by: jfern
1 Replies

2. Shell Programming and Scripting

awk loop using array:wish to store array values from loop for use outside loop

Here's my code: awk -F '' 'NR==FNR { if (/time/ && $5>10) A=$2" "$3":"$4":"($5-01) else if (/time/ && $5<01) A=$2" "$3":"$4-01":"(59-$5) else if (/time/ && $5<=10) A=$2" "$3":"$4":0"($5-01) else if (/close/) { B=0 n1=n2; ... (2 Replies)
Discussion started by: klane
2 Replies

3. UNIX for Dummies Questions & Answers

Trouble understand and using for loop

Good evening all I have what might be a simple problem to solve but I do not know how to solve it myself. I am writing a bash script and my code looks something like this: mp3=`ls | grep \.mp3` for f in $mp3 do echo $f done Basically what I want to do is look through the current... (4 Replies)
Discussion started by: mistsong1
4 Replies

4. UNIX for Dummies Questions & Answers

Loop Counting Question

I figured this out, but I wanted to pose the question. I was writing a while loop that required counting the amount of times the job had run, for example. An example below is what I had: variable=0 while : do variable = `expr $variable + 1` done That didn't do what I... (4 Replies)
Discussion started by: phunk
4 Replies

5. UNIX for Dummies Questions & Answers

Trouble displaying parameters passed into a for loop

#!/bin/bash function check_num_args() { if ; then echo "Please provide a file name" else treat_as_file $* fi } function treat_as_file() { numFiles=$# for((i=1;i<=$numFiles;i++));do echo $i ... (3 Replies)
Discussion started by: kikilahooch
3 Replies

6. Shell Programming and Scripting

Trouble with a file path as awk output in for loop

When I run the following command in the shell it works fine. It prints a city name and then a path for a file. ~$ for i in `awk -F':' '{print $0}' /home/knoppix/Desktop/data/subs | grep -m 1 $ city | sed "s/:/ /"` >do >echo $i >done Now, when I place it in this shell script (sh) it prints... (6 Replies)
Discussion started by: afroCluster
6 Replies

7. Shell Programming and Scripting

counting the lines of diff files in loop

i have two file. i want to count the lines of each file one by one in loop and compare it. can any one pls help me on this? (1 Reply)
Discussion started by: Aditya.Gurgaon
1 Replies

8. Shell Programming and Scripting

for loop syntax trouble

i don't get what's wrong here. i'm writing a shell script that takes 1 argument (a number) from the command-line, but it's throwing an error: Syntax error: Bad for loop variable doesn't make much sense for (( i = 1; i = ${1}; i++ )) # error points to this line everytime do echo... (9 Replies)
Discussion started by: visitorQ
9 Replies

9. Shell Programming and Scripting

Loop Trouble

Can anyone tell me what's wrong with my code here? I'm experiencing weird behavior... I am using 'j' to go down a list filenames saved in a .txt file and prompting the user whether or not she would like to delete each one. This works all well and fine the first run through, but then instead of... (2 Replies)
Discussion started by: RSymphony
2 Replies

10. Shell Programming and Scripting

Start more than one database - trouble with for loop

I have seen this done before - and maybe there is a better way too. I want to be abe to use a for loop (or other better method) to loop through the database instance names that are part of the script - not an external file where a read might be ok. Here is what I have and I know won't work -... (5 Replies)
Discussion started by: dave-mentor
5 Replies
Login or Register to Ask a Question