繁体   English   中英

不确定为什么1个printf语句打印两次

[英]Not sure why 1 printf statement prints twice

更新

我以为这个代码块给我两次打印printf语句时出错,但是我注释掉了代码中的所有内容,并且一切正常! 那么,问题似乎出在我正在使用进程ID进行的工作中。 这是完整的代码:

#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;

}

我期望的输出是这样的:

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

但是我得到了以下输出:

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

子进程的父进程可能会第二次打印该序列吗?

是的,一旦父进程对子进程进行了wait()处理,它将继续沿代码路径向下并打印序列。

您想要的是:

// ....
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);
}

 wait(NULL);

您需要退出/返回。 父母已经完成了抚养孩子的工作,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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