简体   繁体   中英

Not sure why 1 printf statement prints twice

UPDATE

I thought this code block was giving me an error printing a printf statement out twice, but I commented out everything in my code BESIDES this and it worked just fine! What seems to be the issue then is the work I am doing with process IDs. Here is the entire code:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
pid_t pid, pid1;
int n;
int temp;
int stop = 1;

if (argc == 1) {
    fprintf(stderr,"Usage: ./a.out <starting value>\n");

    return -1;
}

n = atoi(argv[1]);

pid = fork();

if (pid < 0) { /* error occurred */
    fprintf(stderr, "Fork Failed");
    return 1;
}

else if (pid == 0) { /* child process */
    pid1 = getpid();
    printf("child: pid = %d\n", pid);
    printf("child: pid1 = %d\n", pid1);
}

else { /* parent process */
    pid1 = getpid();
    printf("parent: pid = %d\n", pid);
    printf("parent: pid1 = %d\n", pid1);
    wait(NULL);
}
while (n!=1) {  
    if (n%2 == 0) {
        printf("%d, ", n);
        temp = (n/2);
        n = temp;
    }else {
        printf("%d, ", n);
        temp = (3*n+1); 
        n = temp;
    }
}
printf("1\n");
return 0;

}

The output I'm expecting is something like:

parent: pid = 1444
parent: pid1 = 1443
child: pid = 0
child: pid = 1444
8, 4, 2, 1

But instead I get this Output:

parent: pid = 1444
parent: pid1 = 1443
child: pid = 0
child: pid = 1444
8, 4, 2, 1
8, 4, 2, 1

Might a child a parent process be printing out the sequence a second time?

Yes, once the parent process has wait() ed on the child process, it continues down the code path and prints the sequence.

What you want is:

// ....
else if (pid == 0) { /* child process */
    pid1 = getpid();
    printf("child: pid = %d\n", pid);
    printf("child: pid1 = %d\n", pid1);

    while (n!=1) {  
        if (n%2 == 0) {
            printf("%d, ", n);
            temp = (n/2);
            n = temp;
        }else {
            printf("%d, ", n);
            temp = (3*n+1); 
            n = temp;
        }
    }
} else { /* parent process */
    pid1 = getpid();
    printf("parent: pid = %d\n", pid);
    printf("parent: pid1 = %d\n", pid1);
    wait(NULL);
}

After

 wait(NULL);

You need an exit/return. The parent has done its job of bringing up the child and is done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM